I have two maps map1 and map2 . I want to merge both maps and then sort in desc order and get top 5. In case of duplicate keys in merge I need to sum the values. I have the following code that works:
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));
But I would like to know if there is a better solution.