Alex Rivera | Logout

Finding Key associated with max Value in a Java Map

Asked 2011-05-06T12:07:30.563
192

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.

Edit
Report

1 Answer

162

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;
    }
}
answered 2011-05-06T12:10:04.010

Your Answer