Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading