使用 Java8 Stream 从地图中查找最高值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42060294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:54:44  来源:igfitidea点击:

Using Java8 Stream to find the highest values from map

javajava-8java-stream

提问by Dumy

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 Streams。你能帮忙吗?

private List<Integer> testStreamMap(Map<Integer, Long> mapGroup) 
{
    List<Integer> listMax = new ArrayList<Integer>();
    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;
}

采纳答案by Holger

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<Integer> testStreamMap(Map<Integer, Long> 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.

在“如何强制 max() 返回 Java 流中的所有最大值?”。您将看到,如果您的输入是普通的Map(例如HashMap),可以廉价地多次迭代,则单遍解决方案要复杂得多并且不值得付出努力。

回答by Bohemian

I'm not sure what half your code is trying to do, but to answer your question as per the title, which I'm guessing was meant to be "find the entry with the highest value":

我不确定你的一半代码试图做什么,但要按照标题回答你的问题,我猜这意味着“找到具有最高价值的条目”

Map.Entry<Integer, Long> maxEntry = map.entrySet().stream()
  .max(Map.Entry.comparingByValue()).get();