2

我正在使用 Guava 的 ArrayListMultimap<K,V>集合映射IntegersStrings. 该类提供了一个称为containsValue(Object value)检查 Multimap 是否包含任何键的指定值的方法。一旦我确定这是真的,检索所述密钥的最佳方法是什么?

ArrayListMultimap<String, Integer> myMap = ArrayListMultimap.create();

if (myMap.containsValue(new Integer(1))
{
   // retrieve the key? 
}
4

1 回答 1

3

containsValue您可以迭代myMap.entries()而不是使用它,它返回所有键值对的集合。返回的集合生成的迭代器遍历一个键的值,然后是第二个键的值,依此类推:

Integer toFind = new Integer(1);
for (Map.Entry<String, Integer> entry: myMap.entries()) {
    if (toFind.equals(entry.getValue())) {
        // entry.getKey() is the first match
    }
}
// handle not found case

如果您查看它的实现,containsValue它只是迭代地图的值,因此使用map.entries()而不是执行此操作的性能map.values()应该大致相同。

public boolean containsValue(@Nullable Object value) {
    for (Collection<V> collection : map.values()) {
      if (collection.contains(value)) {
        return true;
      }
    }

    return false;
}

当然,在一般情况下,给定值不一定有唯一键,因此除非您知道在地图中每个值仅针对单个键出现,否则您需要指定行为,例如,如果您想要第一个键或最后一个键钥匙。

于 2009-09-01T16:12:48.313 回答