Java sort Map by Value descending and then by Key ascending

I have a LinkedHashMap<String, Integer> that I need to order first by the Value descending, and then by the Key ascending. I don’t know how to make the second condition work – I tried .thenComparing and everything I managed to see as a suggestion on the Internet but with no success.

playersSkillsPoints.get(user).entrySet().stream()
        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .forEach(e -> {System.out.printf("- %s <::> %d%n", e.getKey(), e.getValue());

I tried:

.sorted(Map.Entry.comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))

but got:

Cannot resolve method 'thenComparing(Comparator<Entry<K, V>>)'

Any suggestions would be appreciated!

>Solution :

You’re already on the right track but probably just face issues with the generic type inference. If you help the compiler a little it should work, e.g. try this:

...sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
            .thenComparing(Map.Entry.comparingByKey()))

Alternatively create the comparators first, then combine them:

Comparator<Entry<String, Integer>> valueComparator = Map.Entry.comparingByValue();
Comparator<Entry<String, Integer>> keyComparator = Map.Entry.comparingByKey();

...sorted(valueComparator.reversed().thenComparing(keyComparator))

Leave a Reply