javamap最⼤值,使⽤Java8Stream从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?
java streamprivate List testStreamMap(Map mapGroup)
{
List listMax = new ArrayList();
Long frequency = 0L;
for (Integer key : mapGroup.keySet()) {
Long occurrence = (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 Set().stream().max(Map.EntryparingByValue()).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())
ptyList();
long max = mapGroup.values().stream().max(Comparator.naturalOrder()).get();
Set().stream()
.filter(e -> e.getValue() == max)
.map(Map.Entry::getKey)
.List());
}
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.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。