Organizational Research By

Surprising Reserch Topic

collection Java Hashmap: How to get key from value?


If I have the value "foo", and a HashMap ftw for which ftw.containsValue("foo") returnstrue, how can I get the corresponding key? Do I have to loop through the hashmap? What is the best way to do that?

asked Jun 19, 2015 in Core java by rajesh
0 votes
101 views



Related Hot Questions

3 Answers

0 votes
If you choose to use the Commons Collections library instead of the standard Java Collections API, you can achieve this with ease.

The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.

There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidimaps.

Update

If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.

Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.

Update #2

Support for bidi maps with generics can be found in Google Collections and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.
answered Jun 19, 2015 by rajesh
0 votes
If your data structure has many-to-one mapping between keys and values you should iterate over entries and pick all suitable keys:

public static Set getKeysByValue(Map map, E value) {
    Set keys = new HashSet();
    for (Entry entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            keys.add(entry.getKey());
        }
    }
    return keys;
}
In case of one-to-one relationship, you can return the first matched key:

public static T getKeyByValue(Map map, E value) {
    for (Entry entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}
In Java 8:

public static Set getKeysByValue(Map map, E value) {
    return map.entrySet()
              .stream()
              .filter(entry -> Objects.equals(entry.getValue(), value))
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}
Also, for Guava users, BiMap may be useful. For example:

BiMap tokenToChar =
    ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);
answered Jun 19, 2015 by rajesh
0 votes
public class NewClass1 {

    public static void main(String[] args) {
       Map testMap = new HashMap();
        testMap.put(10, "a");
        testMap.put(20, "b");
        testMap.put(30, "c");
        testMap.put(40, "d");
        for (Entry entry : testMap.entrySet()) {
            if (entry.getValue().equals("c")) {
                System.out.println(entry.getKey());
            }
        }
    }
}
answered Jun 19, 2015 by rajesh

...