Ben B. Ben B. - 2 years ago 113
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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download