为了账号安全,请及时绑定邮箱和手机立即绑定

在Java映射中查找与最大值关联的键

在Java映射中查找与最大值关联的键

明月笑刀无情 2019-10-26 12:46:54
获取与映射中的最大值关联的键的最简单方法是什么?我相信,当您想要对应于最大值的键时,Collections.max(someMap)将返回最大键。
查看完整描述

3 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

基本上,您需要遍历地图的条目集,同时记住“当前已知的最大值”和与之相关的键。(当然,或者仅包含两者的条目。)


例如:


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;

    }

}


查看完整回答
反对 回复 2019-10-26
?
www说

TA贡献1775条经验 获得超8个赞

为了完整起见,这是一种Java-8方式


countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();

要么


Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();

要么


Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();


查看完整回答
反对 回复 2019-10-26
?
米脂

TA贡献1836条经验 获得超3个赞

该代码将打印所有具有最大值的键


public class NewClass4 {

    public static void main(String[] args)

    {

        HashMap<Integer,Integer>map=new HashMap<Integer, Integer>();

        map.put(1, 50);

        map.put(2, 60);

        map.put(3, 30);

        map.put(4, 60);

        map.put(5, 60);

        int maxValueInMap=(Collections.max(map.values()));  // This will return max value in the Hashmap

        for (Entry<Integer, Integer> entry : map.entrySet()) {  // Itrate through hashmap

            if (entry.getValue()==maxValueInMap) {

                System.out.println(entry.getKey());     // Print the key with max value

            }

        }


    }

}


查看完整回答
反对 回复 2019-10-26
  • 3 回答
  • 0 关注
  • 424 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信