Java Collection - 独特的关键和独特的价值

jav*_*vaj 28 java collections

我需要一个可以根据键查找值的集合,反之亦然.对于每个值,都有一个键,每个键都有一个值.是否存在可以使用的数据结构?

Mic*_*ers 33

来自Google GuavaBiMap看起来很适合你.

bimap(或"双向映射")是一种映射,它保留其值及其键的唯一性.此约束使bimaps支持"反向视图",这是另一个包含与此bimap相同的条目但具有反向键和值的bimap.

或者来自Apache Commons CollectionsBidiMap:

定义允许在键和值之间进行双向查找的映射.

此扩展Map表示一个映射,其中键可以查找值,值可以同样容易地查找键.此接口扩展Map,因此可以在需要地图的任何地方使用.界面提供了反向地图视图,可以完全访问两个方向BidiMap.


Cra*_*lin 8

您可以使用BIMAPEclipse的集合(前身为GS集合).

BiMap是一个允许用户从两个方向执行查找的地图.BiMap中的键和值都是唯一的.

主要实施是HashBiMap.

inverse()

BiMap.inverse() 返回一个视图,其中交换键类型和值类型的位置.

MutableBiMap<Integer, String> biMap =
  HashBiMap.newWithKeysValues(1, "1", 2, "2", 3, "3");
MutableBiMap<String, Integer> 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));
Run Code Online (Sandbox Code Playgroud)

put()

MutableBiMap.put()行为类似于Map.put()常规地图,除非在添加重复值时抛出.

MutableBiMap<Integer, String> biMap = HashBiMap.newMap();
biMap.put(1, "1"); // behaves like a regular put()
biMap.put(1, "1"); // no effect
biMap.put(2, "1"); // throws IllegalArgumentException
Run Code Online (Sandbox Code Playgroud)

forcePut()

这样的行为MutableBiMap.put(),但它在将键值对放入映射之前以静默方式删除具有相同值的映射条目.

MutableBiMap<Integer, String> 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);
Run Code Online (Sandbox Code Playgroud)

注意:我是Eclipse Collections的提交者.