Java Collection – 独特的关键和独特的价值
我需要一个可以根据键查找值的集合,反之亦然。 对于每个值,都有一个键,每个键都有一个值。 是否有可以使用的数据结构?
来自Google Guava的BiMap看起来很适合你。
bimap(或“双向映射”)是一种保留其值及其键值的唯一性的映射。 此约束使bimaps支持“反向视图”,这是另一个包含与此bimap相同的条目但具有反向键和值的bimap。
或者来自Apache Commons Collections的BidiMap :
定义允许在键和值之间进行双向查找的映射。
此扩展
Map
表示一个映射,其中键可以查找值,值可以轻松地查找键。 此接口扩展了Map
,因此可以在需要地图的任何地方使用。 界面提供逆映射视图,可以完全访问BidiMap
两个方向。
您可以使用Eclipse Collections (以前的GS Collections)中的BiMap 。
BiMap
是一个允许用户从两个方向执行查找的地图。 BiMap中的键和值都是唯一的。
主要实现是HashBiMap
。
inverse()
BiMap.inverse()
返回一个视图,其中交换了键类型和值类型的位置。
MutableBiMap biMap = HashBiMap.newWithKeysValues(1, "1", 2, "2", 3, "3"); MutableBiMap inverse = biMap.inverse(); Assert.assertEquals("1", biMap.get(1)); Assert.assertEquals(1, inverse.get("1")); Assert.assertTrue(inverse.containsKey("3")); Assert.assertEquals(2, inverse.put("2", 4));
put()
MutableBiMap.put()
在常规地图上的行为类似于Map.put()
,除非在添加重复值时抛出。
MutableBiMap biMap = HashBiMap.newMap(); biMap.put(1, "1"); // behaves like a regular put() biMap.put(1, "1"); // no effect biMap.put(2, "1"); // throws IllegalArgumentException
forcePut()
它的行为类似于MutableBiMap.put()
,但它在将键值对放入映射之前以静默方式删除具有相同值的映射条目。
MutableBiMap biMap = HashBiMap.newMap(); biMap.forcePut(1, "1"); // behaves like a regular put() biMap.forcePut(1, "1"); // no effect biMap.put(1, "2"); // replaces the [1,"1"] pair with [1, "2"] biMap.forcePut(2, "2"); // removes the [1, "2"] pair before putting Assert.assertFalse(biMap.containsKey(1)); Assert.assertEquals(HashBiMap.newWithKeysValues(2, "2"), biMap);
注意:我是Eclipse Collections的提交者。
接受的答案提到了BiMap
,但它与Google Guava库的关系变得更新了 。
BiMap
是Map
- 允许您使用
inverse()
查看“逆”BiMap
- 确保值是唯一的,使
values()
成为Set
所以,你最终可以得到这样的代码:
final BiMap 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
这个对象的一些警告:
- 您将无法添加非唯一值,或者您将获得
IllegalArgumentException
。 您可以使用forcePut(key, value)
,但这将覆盖现有的键值对 。