Java Hashmap: How to get key from value?

前端 未结 30 1846
忘掉有多难
忘掉有多难 2020-11-22 02:14

If I have the value \"foo\", and a HashMap ftw for which ftw.containsValue(\"foo\") returns true, how can I

30条回答
  •  你的背包
    2020-11-22 03:17

    I'm afraid you'll just have to iterate your map. Shortest I could come up with:

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

提交回复
热议问题