2009-09-01 81 views
2

我正在使用Guava的ArrayListMultimap<K,V>集合來映射IntegersStrings。該類提供了一種名爲containsValue(Object value)的方法,該方法檢查Multimap是否包含任何鍵的指定值。一旦我確定這是真的,檢索所述密鑰的最佳方法是什麼?檢索ArrayListMultimap鍵

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

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

回答

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

當然,在一般情況下,有沒有必要給定值的唯一密鑰因此,除非你知道,在你的地圖上的每個值僅發生針對單個鍵,你就需要指定的行爲,例如如果你想要第一個鍵或最後一個鍵。