Sorting a Map by values instead of keys

This post is motivated by ““Sorting a list or array of numbers by frequency of occurrences in Java”

Sorting a Map by Keys

Sorting a map by its keys is straightforward

Sorting a Map by its Values – Pre Java 8

If you want to sort by age in reverse, i.e. descending order then swap o1 and o2


Sorting a Map by its Values – Java 8 onwards

The “sortByAgeAscending” method becomes

OR the “.sorted(…..)” can be written as

for sorting by age descending

Java Interview FAQs

800+ Java Interview Q&As