Collections

Java HashMap sort by Values Example

Java HashMap sort by Values Example shows how to sort HashMap by values in Java. This example also shows how to sort HashMap by values using LinkedHashMap and Comparator.

How to sort HashMap by values in Java?

HashMap by definition does not maintain the order of the inserted elements. So even if we sort it, it might not return the elements in the same order. From HashMap Javadoc,

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

If you want to sort HashMap by key, you can use implementation of SortedMap like TreeMap, which will automatically sort the Map by keys. Sorting HashMap by values will need a collection which maintains order like LinkedHashMap.

a) Sorting HashMap by value if you want only values

If you want only values of the HashMap to be sorted in a particular order and don’t need whole map, then it can be done with the help of Set as given below.

Output

In above example, first we took all the HashMap values into the List. We then used sort method of Collections class to sort the List. We also provided custom Comparator so that value objects (in our case Integer objects) can be compared to one another while being sorted.

How to sort HashMap by value in descending order?

If you want to sort HashMap by values in descending order change the line which sorts the list as given below.

Output

b) Sorting HashMap by values if you want both keys and values

In the above example, we sorted the HashMap values. If you want a Map containing keys and values which is sorted by values based on the original HashMap, you need to sort the HashMap and put keys and values in a collection which maintains the element order such as LinkedHashMap as given below.

Output

Note:

If the HashMap contains object of a custom class as value, the custom class must implement Comparable interface for above method to work.

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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