本文介绍了使用 Java8 Stream 从地图中查找最高值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下方法来查找映射到最高值的键并尝试转换为 java Streams.你能帮忙吗?

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<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;
}

推荐答案

您可以通过

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());
}

如何强制 max() 返回 ALL 中讨论了在单次通过中获取流的所有最大值的解决方案Java Stream 中的最大值?".如果您的输入是一个普通的Map(例如HashMap),可以廉价地迭代多次.

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.

这篇关于使用 Java8 Stream 从地图中查找最高值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:28