Java Hashmap: How to get key from value?

前端 未结 30 2346
忘掉有多难
忘掉有多难 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:18

    For Android development targeting API < 19, Vitalii Fedorenko one-to-one relationship solution doesn't work because Objects.equals isn't implemented. Here's a simple alternative:

    public  K getKeyByValue(Map map, V value) {
        for (Map.Entry entry : map.entrySet()) {
                if (value.equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    

提交回复
热议问题