利用 Guava 的 BiMap 实现双向 Map

Java 自带的 Map 只是 K-V 型的单向映射,一般情况下是够用的了。
但是最近做项目发现有一个情景,一方面要根据 K 拿到 V,另一方面,又需要从 V 反推到 K。如果用 Java 自带的 Map 来实现,就是做两个 Map 或者遍历 V 找到 K,感觉复杂了点。

Guava 的 BiMap

这个时候,有个工具类值得使用了:Guava 的 BiMap
使用方法: value 不可以有相同的 key

1
2
3
4
5
6
7
8
9
10
11
12
BiMap<String, String> biMap = HashBiMap.create();
// value可以作为Key,即value不可以有多个对应的值
biMap.put("hello", "world");
biMap.put("123", "tell");
biMap.put("123", "none"); // 覆盖tell
// biMap.put("abc", "world"); 失败
// 下面是强制替换第一对
biMap.forcePut("abc", "world");
System.out.println(biMap.size()); // 2
System.out.println(biMap.get("hello"));// null
System.out.println(biMap.get("abc")); // world
System.out.println(biMap.get("123")); // none

键值对互换得到新的 BiMap

1
2
3
4
5
// 键值对互换
BiMap<String, String> inverseMap = biMap.inverse();
System.out.println(inverseMap.get("world")); // abc
System.out.println(inverseMap.get("tell")); // null
System.out.println(inverseMap.get(null)); // null

参考链接