views:

38

answers:

1

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.

+1  A: 

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.

Péter Török