Merging, sorting and limit Map streams using Java 8 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&lt;String, Long&gt; 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) -&gt; v1,
            LinkedHashMap::new));


But I would like to know if there is a better solution.
The question for a "better" solution is bound to be quite opinion-based. As far as the actual code goes, I think you are quite close to the optimum. As for readability... well, Roland already shared his initial thoughts and I totally agree. This is bound to be a nightmare for the poor maintenance programmer.

Thus: a suggestion which is nothing new, but just a little rearangement:

private Map&lt;String, Long&gt; getHistogramTopFive(Map&lt;String, Long&gt; map1, Map&lt;String, Long&gt; map2) {
    Map&lt;String, Long&gt; mergedMap = (Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum)));

    Map&lt;String, Long&gt; topFive = mergedMap.entrySet().stream()
        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .limit(5)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (v1,v2) -&gt; v1,
                LinkedHashMap::new));

    return topFive;
}


By putting it into a method and naming this method, you document your business intention. Furthermore, by breaking up the long command chain with a new mergedMap variable in between, the code gains much in readability.

The additional line-breaks in the second part are what I consider best practices in streaming API: each new operation on a new line.