Given a Map, how do I look up all keys associated with a particular value?
For example:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 5);
map.put(2, 2);
map.put(3, 5);
Collection<Integer> keys = map.values(5); // should return {1, 3}
I'm looking for something similar to Google Collections' BiMap where values are not unique.
To retrieve the set of keys from HashMap, use the keyset() method. However, for set of values, use the values() method.
Example: Get key for a given value in HashMap Here, the entrySet() method returns a set view of all the entries. Inside the if statement we check if the value from the entry is the same as the given value. And, for matching value, we get the corresponding key.
With plain java.util.Map
implementations, I am afraid you must iterate through the map entries and test each value:
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue().equals(desiredValue) {
keys.add(entry.getKey());
}
}
If you want better performance, you may want to build up a parallel mapping from values to lists of keys. I don't know of any existing collection doing this, but it should not be difficult to implement.
From Java 8 onwards you can use map.forEach:
map.forEach((k,val) -> {
if (val.equals(desiredValue) {
keys.add(k);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With