Sort Map as per values – Java Program

Objective: Given a map which has String as key and Integer as value. Write a program to sort the map in descending order according to the values.

Example:

Given Map:
Joe : 1000 Earl : 1200 Carl : 2000 Brad : 1510 Dow : 500

Sorted Map:
Carl : 2000 Brad : 1510 Earl : 1200 Joe : 1000 Dow : 500

Approach:

  • Construct the List out of the given Map of type Map.Entry<String, Integer>.
  • Sort the list by overriding the compare function in Comparator. Inside compare function – compare the map values.
  • Initialize the LinkedHashMap (now order matters since we are sorting the list).
  • Iterate the list and fill the linked hash map

Complete Code:

Output:

Given Map:
Joe : 1000 Earl : 1200 Carl : 2000 Brad : 1510 Dow : 500
Sorted Map:
Carl : 2000 Brad : 1510 Earl : 1200 Joe : 1000 Dow : 500