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

Dum*_*umy 14 java java-8 java-stream

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

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;
}
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 22

你可以通过一键获得

Integer max=mapGroup.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();
Run Code Online (Sandbox Code Playgroud)

但遗憾的是,没有内置函数可以获得所有等效的最大值.

最简单,直接的解决方案是首先找到最大值,然后检索映射到该值的所有键:

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());
}
Run Code Online (Sandbox Code Playgroud)

在" 如何强制max()返回Java流中的所有最大值? "中讨论了在单个过程中获取流的所有最大值的解决方案".您将看到单通道解决方案要复杂得多,如果您的输入是普通的Map(例如HashMap),则可能不值得努力,可以廉价地多次迭代.


Boh*_*ian 21

我不确定你的代码试图做了哪一半,但是根据标题来回答你的问题,我猜这是为了"找到具有最高价值的条目":

Map.Entry<Integer, Long> maxEntry = map.entrySet().stream()
  .max(Map.Entry.comparingByValue()).get();
Run Code Online (Sandbox Code Playgroud)

  • @Bohemian 这将只返回单个键,如何返回键列表 (2认同)
  • @Dumy你的意思是1和**3**(你的例子中都有4个)? (2认同)