java map 最大值_查找与Java Map中的最大值关联的密钥

问题

获取 Map 中最大值关键字的最简单方法是什么?

我相信当你需要与最大值对应的键时,Collections.max(someMap)将返回最大键。

#1 热门回答(98 赞)

基本上你需要迭代 Map 的入口集,记住"当前已知的最大值"和与之关联的密钥。 (或者只是包含两者的条目。)

例如:

Map.Entry maxEntry = null;

for (Map.Entry entry : map.entrySet())

{

if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)

{

maxEntry = entry;

}

}

#2 热门回答(60 赞)

为了完整起见,这是一种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();

#3 热门回答(40 赞)

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

public class NewClass4 {

public static void main(String[] args)

{

HashMapmap=new HashMap();

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 entry : map.entrySet()) { // Itrate through hashmap

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

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

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值