使用Java8 Stream从map中查找最高值
我编写了以下方法来查找映射到最高值的键并尝试转换为java Stream
。 你能帮忙吗?
private List testStreamMap(Map mapGroup) { List listMax = new ArrayList(); 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();
但遗憾的是,没有内置函数可以获得所有等效的最大值。
最简单,直接的解决方案是首先找到最大值,然后检索映射到该值的所有键:
private List testStreamMap(Map 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流中的所有最大值? ”中讨论了在单次传递中获取流的所有最大值的解决方案? ”。 你会发现单通道解决方案要复杂得多,如果你的输入是一个普通的Map
(例如HashMap
),它不值得努力,它可以廉价地多次迭代。
我不确定你的代码试图做了哪一半,但是根据标题回答你的问题,我猜这是为了“找到价值最高的条目” :
Map.Entry maxEntry = map.entrySet().stream() .max(Map.Entry.comparingByValue()).get();