Be the first user to complete this post

  • 0
Add to List
Medium

472. 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

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