在 Java Map 中查找与最大值关联的键 [英] Finding Key associated with max Value in a Java Map

查看:28
本文介绍了在 Java Map 中查找与最大值关联的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取与地图中最大值关联的键的最简单方法是什么?

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

我相信 Collections.max(someMap) 会返回最大的 Key,当你想要对应于最大值的键时.

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.)

例如:

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

这篇关于在 Java Map 中查找与最大值关联的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆