Finding Key associated with max Value in a Java Map

Ben B. picture Ben B. · May 6, 2011 · Viewed 236.8k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · May 6, 2011

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;
    }
}