What's the quickest way to remove an element from a Map by value in Java?

The correct and fast one-liner would actually be:

while (map.values().remove(valueObject));

Kind of strange that most examples above assume the valueObject to be unique.


Without using a Bi-directional map (commons-collections and google collections have them), you're stuck with iterating the Map


Here's the one-line solution:

map.values().remove(valueToRemove);

That's probably faster than defining your own iterator, since the JDK collection code has been significantly optimized.

As others have mentioned, a bimap will have faster value removes, though it requires more memory and takes longer to populate. Also, a bimap only works when the values are unique, which may or may not be the case in your code.