Java Hashmap: How to get key from value?

前端 未结 30 1882
忘掉有多难
忘掉有多难 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 02:59

    I think keySet() may be well to find the keys mapping to the value, and have a better coding style than entrySet().

    Ex:

    Suppose you have a HashMap map, ArrayList res, a value you want to find all the key mapping to , then store keys to the res.

    You can write code below:

        for (int key : map.keySet()) {
            if (map.get(key) == value) {
                res.add(key);
            }
        }
    

    rather than use entrySet() below:

        for (Map.Entry s : map.entrySet()) {
            if ((int)s.getValue() == value) {
                res.add((int)s.getKey());
            }
        }
    

    Hope it helps :)

提交回复
热议问题