Ben B. Ben B. - 1 year ago 48
Java Question

Finding Key associated with max Value in a Java Map

What is the easiest way to get key associated with the max value in a map?

I believe that Collections.max(someMap) will return the max Key, when you want the key that corresponds to the max value.


Basically you'd need to iterate over the map's entry set, remembering both the "currently known maximum" and the key associated with it. (Or just the entry containing both, of course.)

For example:

Map.Entry<Foo, Bar> maxEntry = null;

for (Map.Entry<Foo, Bar> entry : map.entrySet())
    if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
        maxEntry = entry;