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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: