使用 Java8 流从映射中查找最大值

2022-09-02 19:22:12

我编写了以下方法来查找映射到最高值的键,并尝试转换为java s。你能帮忙吗?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;
}

答案 1

您可以通过以下方式获取单个密钥

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

但不幸的是,没有内置函数来获取所有等效的最大值。

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

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() 返回 Java 流中的所有最大值?”中进行了讨论。您将看到单通道解决方案要复杂得多,如果您的输入是普通的(例如),则不值得付出努力,这可以廉价地多次迭代。MapHashMap


答案 2

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

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

推荐