allows you to view the "inverse" BiMap<V, K> with inverse()
ensures that values are unique, making values() a Set
因此,您可以得到如下代码:
final BiMap<String, Integer> biMap = HashBiMap.create();
biMap.put("word", 1);
biMap.put("alpha", 2);
System.out.println(biMap.get("word")); // prints 1
System.out.println(biMap.inverse().get(1)); // prints word
A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.
Defines a map that allows bidirectional lookup between key and values.
This extended Map represents a mapping where a key may lookup a value and a value may lookup a key with equal ease. This interface extends Map and so may be used anywhere a map is required. The interface provides an inverse map view, enabling full access to both directions of the BidiMap.
# 1 楼答案
公认的答案提到了
BiMap
,但它已经变成了more up-to-date与谷歌番石榴图书馆因此,您可以得到如下代码:
此对象的一些注意事项:
IllegalArgumentException
。您可以使用forcePut(key, value)
,但这将override the existing key-value pair李># 2 楼答案
来自Google Guava的BiMap看起来适合你
或来自Apache Commons Collections的BidiMap:
# 3 楼答案
您可以使用来自Eclipse Collections(以前是GS集合)的BiMap
BiMap
是一个允许用户从两个方向执行查找的映射。BiMap中的键和值都是唯一的主要实现是
HashBiMap
inverse()
BiMap.inverse()
返回交换键类型和值类型位置的视图put()
MutableBiMap.put()
的行为类似于常规映射上的Map.put()
,只是在添加重复值时抛出forcePut()
其行为类似于
MutableBiMap.put()
,但在将键值对放入映射之前,它会以静默方式删除具有相同值的映射项注意:我是Eclipse集合的提交者