How to Sort Map based on Values in java ?

By | June 13, 2020

In this post, we will learn How to Sort Map based on Values in java? 

Here I have shown a couple of cases, In the first case, Map values are Strings, and second case Map values are Custom objects.

Finally, We will also look at Sort Map based on Keys Using Java 8 stream API and Lambda.

Sorting Map based on Values, when Values contains Strings:

Output of the above program:

Original Map::::
10033 KK
13234 BEAN
12004 WEST
10004 AK
10234 Sean
11004 MARK
11724 ANTONY
Map sorted based on Values::::
10004 AK
11724 ANTONY
13234 BEAN
10033 KK
11004 MARK
10234 Sean
12004 WEST

 

Sorting Map based on Values, when Values contains Custom Objects:

Sort Map based on Keys Using Java 8 stream API and Lambda.

 

Output of the above program:

Original Map::::
10304 Employee [employeeId=10304, employeeName=West, deptName=Admin, salary=20000.0]
11009 Employee [employeeId=11009, employeeName=Lussy, deptName=Surveillance, salary=70000.0]
11106 Employee [employeeId=11106, employeeName=Frank, deptName=Risk, salary=10000.0]
10005 Employee [employeeId=10005, employeeName=Sam, deptName=Finance, salary=40000.0]
10007 Employee [employeeId=10007, employeeName=Hamid, deptName=Asset Management, salary=80000.0]
12301 Employee [employeeId=12301, employeeName=Sean, deptName=IT, salary=30000.0]
12303 Employee [employeeId=12303, employeeName=Abhay, deptName=Finance, salary=10000.0]
Map sorted based on Values::::
12303 Employee [employeeId=12303, employeeName=Abhay, deptName=Finance, salary=10000.0]
11106 Employee [employeeId=11106, employeeName=Frank, deptName=Risk, salary=10000.0]
10007 Employee [employeeId=10007, employeeName=Hamid, deptName=Asset Management, salary=80000.0]
11009 Employee [employeeId=11009, employeeName=Lussy, deptName=Surveillance, salary=70000.0]
10005 Employee [employeeId=10005, employeeName=Sam, deptName=Finance, salary=40000.0]
12301 Employee [employeeId=12301, employeeName=Sean, deptName=IT, salary=30000.0]
10304 Employee [employeeId=10304, employeeName=West, deptName=Admin, salary=20000.0] 

 

You May Also Like:

Difference between List and Set in Java Collection ?
When should we choose LinkedList over ArrayList for a given Scenario and Why?
Is there concurrent version for TreeMap and TreeSet in Java Collections Framework?
What is difference between Collections. Sort() and Arrays.sort()? Which one is better with respect to time efficiency?
What are fail-fast and fail-safe Iterator?
What is difference between Iterator and LisIterator?
Why Prime Numbers are considered in writing certain algorithms like hashcode()?
What all collections utilizes hashCode() method in java?

That’s all about How to Sort Map based on Values in java?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.