我有两个地图 Map<String, Long>
。我想合并这两个地图,按降序排序,并获取前5个。如果合并中存在重复键,则需要将值相加。以下是可以正常工作的代码:
Map<String, Long> topFive = (Stream.concat(map1.entrySet().stream(),
map2.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
Long::sum)))
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(5)
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> v1,
LinkedHashMap::new));
但我想知道是否有更好的解决方案。