0

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!

1 Answers1

4

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))
Thomas
  • 87,414
  • 12
  • 119
  • 157
  • Worked great, I knew about the second option but the first suggestion seems much better option, just didn't know how to properly set it up – Nataliikaa PetroOwwa Nov 10 '22 at 08:23
  • 1
    @NataliikaaPetroOwwa great it worked :). Tbh, I actually like the second option better as it's more readable :D – Thomas Nov 10 '22 at 08:28