Sort a Map based on its value in Java

Β·

1 min read

Suppose there is a map with values : {a=5 , z=6 , b=12} and you want to sort based on its values as {b=12 , z=6 , a=5} (descending order)

raycast-untitled (9).png

Now if we want to sort the map based on values of map entry then we need to use PriorityQueue class. And here we need a helper class ie Pair class.

In order to sort in descending order you need use this PriorityQueue and need to give this comparator to so that it works based on the comparator given to it.

raycast-untitled (13).png

Now iterate over map and keep adding Pair of key value from map as shown.

Note that Pair must be of reverse order of map key values. suppose your map is of type then Pair class be of type

raycast-untitled (14).png

Now you can see that all values are sorted in PriorityQueue based on values in descending order… And if you need to sort in ascending order just interchange the comparator b.getKey()-a.getKey() to a.getKey()-b.getKey() .

Β