您可以通过以下方式获得一个钥匙
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()返回JavaStream中的所有最大值?
”中讨论了单次获取流的所有最大值的解决方案。”。您将看到,如果您的输入是普通的
Map(例如
HashMap),可以很便宜地进行多次迭代,那么单遍解决方案将变得更加复杂并且不值得付出努力。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)