有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java集合唯一键和唯一值

我需要一个集合,可以根据键查找值,反之亦然。每个值都有一个键,每个键都有一个值。有没有现成的数据结构可以做到这一点


共 (3) 个答案

  1. # 1 楼答案

    公认的答案提到了BiMap,但它已经变成了more up-to-date与谷歌番石榴图书馆

    A BiMap<K, V> is a Map<K, V> that

    • 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
    

    此对象的一些注意事项:

  2. # 2 楼答案

    来自Google GuavaBiMap看起来适合你

    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.

    或来自Apache Commons CollectionsBidiMap

    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.

  3. # 3 楼答案

    您可以使用来自Eclipse Collections(以前是GS集合)的BiMap

    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));
    

    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
    

    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);
    

    注意:我是Eclipse集合的提交者