Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 415
Gili Avatar asked Oct 23 '10 20:10

Gili


People also ask

How do I get a list of keys on a map?

To retrieve the set of keys from HashMap, use the keyset() method. However, for set of values, use the values() method.

Can we get key from value in HashMap?

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.


1 Answers

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);
      }
});
like image 150
Péter Török Avatar answered Nov 02 '22 19:11

Péter Török