java map 最大值,使用Java8 Stream从map中查找最高值

I wrote following method to find the keys mapped to the highest values and trying to convert to java Streams. Can you please help?

private List testStreamMap(Map mapGroup)

{

List listMax = new ArrayList();

Long frequency = 0L;

for (Integer key : mapGroup.keySet()) {

Long occurrence = mapGroup.get(key);

if (occurrence > frequency) {

listMax.clear();

listMax.add(key);

frequency = occurrence;

} else if (occurrence == frequency) {

listMax.add(key);

}

}

return listMax;

}

解决方案

You can get a single key via

Integer max=mapGroup.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();

but unfortunately, there is no built-in function for getting all equivalent maximums.

The simplest, straight-forward solution is to find the maximum value first and retrieve all keys mapping to that value afterwards:

private List testStreamMap(Map mapGroup) {

if(mapGroup.isEmpty())

return Collections.emptyList();

long max = mapGroup.values().stream().max(Comparator.naturalOrder()).get();

return mapGroup.entrySet().stream()

.filter(e -> e.getValue() == max)

.map(Map.Entry::getKey)

.collect(Collectors.toList());

}

Solutions for getting all maximum values of a stream in a single pass, are discussed in “How to force max() to return ALL maximum values in a Java Stream?”. You will see that single-pass solutions are much more complicated and not worth the effort if your input is an ordinary Map (e.g. HashMap), which can be iterated multiple times cheaply.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值