如果我有值“foo”,和一个HashMap<String> ftw,其中ftw. containsvalue(“foo”)返回真,我怎么能得到相应的键?我需要遍历hashmap吗?最好的方法是什么?


当前回答

Iterator<Map.Entry<String,String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String,String> entry = iterator.next();
    if (entry.getValue().equals(value_you_look_for)) {
        String key_you_look_for = entry.getKey();
}
} 

其他回答

需要注意的是,由于这个问题,Apache Collections支持通用的BidiMaps。因此,一些投票最多的答案在这一点上不再准确。

对于支持重复值(一对多场景)的Serialized BidiMap,也可以考虑MapDB.org。

如果你想从value中获取key,最好使用bidimap(双向映射),你可以在O(1)时间内从value中获取key。 但是,这样做的缺点是你只能使用唯一的键集和值集。 在java中有一个数据结构叫Table,它就是map of maps 表< A, B, C > == map < A, map < B, C > > 这里通过查询T.row(a);可以得到map<B,C>,通过查询T.column(B);也可以得到map< a,C>;

在你的特殊情况下,插入C作为某个常数。

它是< a1, b1, 1 > < a2, b2, 1 >,…

如果你通过t。row(a1)——>返回——>的map get keyset这个返回的map。

如果你需要找到键值,那么T.column(b2)——>返回map of——> get keyset of返回map。

与前一种情况相比的优点:

可以使用多个值。 在使用大型数据集时效率更高。

你可以使用下面的:

public class HashmapKeyExist {
    public static void main(String[] args) {
        HashMap<String, String> hmap = new HashMap<String, String>();
        hmap.put("1", "Bala");
        hmap.put("2", "Test");

        Boolean cantain = hmap.containsValue("Bala");
        if(hmap.containsKey("2") && hmap.containsValue("Test"))
        {
            System.out.println("Yes");
        }
        if(cantain == true)
        {
            System.out.println("Yes"); 
        }

        Set setkeys = hmap.keySet();
        Iterator it = setkeys.iterator();

        while(it.hasNext())
        {
            String key = (String) it.next();
            if (hmap.get(key).equals("Bala"))
            {
                System.out.println(key);
            }
        }
    }
}

在java8

map.entrySet().stream().filter(entry -> entry.getValue().equals(value))
    .forEach(entry -> System.out.println(entry.getKey()));

让我们看看我的例子

Map<String, String> mapPeopleAndCountry = new HashMap<>();
mapPeopleAndCountry.put("Matis", "Lithuania");
mapPeopleAndCountry.put("Carlos", "Honduras");
mapPeopleAndCountry.put("Teboho", "Lesotho");
mapPeopleAndCountry.put("Marielos", "Honduras");


List<String> peopleInHonduras = mapPeopleAndCountry.keySet()
    .stream()
    .filter(r -> mapPeopleAndCountry.get(r)
                .equals("Honduras"))
    .stream(Collectors.toList());

// will return ["Carlos", "Marielos"]

注:未经测试,可能含有错别字