Map: How to get all keys associated with a value?

Given a map, how do I find all the keys associated with a particular value?

For instance:

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 am looking for something similar to BiMap Google Collections, where the values ​​are not unique.

+5
source share
1 answer

I am afraid that with simple java.util.Map implementations you should iterate over the map entries and check each value:

 for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue().equals(desiredValue) { keys.add(entry.getKey()); } } 

If you need better performance, you can create a parallel mapping of values ​​from key lists. I do not know of any existing collection doing this, but it should not be difficult to implement.

Starting with Java 8, you can use map.forEach:

 map.forEach((k,val) -> { if (val.equals(desiredValue) { keys.add(k); } }); 
+11
source

All Articles