HashMap.containsValue - What's the point?

A map maps a key to a value. If you have a value and you know the map contains this value, why do you need the key anymore?

On the other hand, if you really need the key or you have just a property of the value, you can iterate the entrySet(), check the value and return the key if found:

for (Map.Entry<Index,Value> entry : map.entrySet()) {
  if (entry.getValue().getXy().equals(xy)) {
    return entry.getKey();
  }
}

A map is a key to value store. Saying a value is contained is only given as an indication. I think that to have the bijective link allowing you to retrieve key from value, you'll have to rely upon things like BiMap from google-collections


You aren't required to traverse it afterwards. containsValue() is helpful in situations where you don't need to know precisely where the value you, but rather when you only need to know if it's already in the Map. In situations where you need to know precisely where in the Map the value is, don't bother using containsValue() -- jump right to the iterator and find it.

Tags:

Java

Hashmap