今天介绍一个BiMap的小例子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; public class TryBiMap { public static void main(String[] args) { BiMap<String, String> aBiMap = HashBiMap.<String, String>create(); aBiMap.put("abc", "def"); aBiMap.put("defe", "abcd"); System.out.println(aBiMap); // output: {abc=def, defe=abcd} System.out.println(aBiMap.get("abc")); // output: def // this line will throw a runtime exception // because there is "defe":"abcd" already. This record impacts BiMap.inverse. // aBiMap.put("abc", "abcd"); // But we can use BiMap.forcePut to put the record of "abc":"abcd" // And the record "defe":"abcd" will be erased. aBiMap.forcePut("abc", "abcd"); // Use BiMap.inverse() to get a inversed bimap. aBiMap = aBiMap.inverse(); System.out.println(aBiMap); // output: {abcd=abc} System.out.println(aBiMap.get("abcd")); // output: abc } } |