Skip to content

Java HashMap sort by Values Example

Java HashMap sort by values example shows how to sort HashMap by values in Java using the sort method, the LinkedHashMap class. and a Comparator.

How to sort HashMap by values in Java?

The HashMap class 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 the implementation of SortedMap like TreeMap, which will automatically sort the Map by keys. Sorting HashMap by values will need a collection that 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 the whole map, then it can be done with the help of the Set as given below.

Output

In the above example, first, we took all the HashMap values into the List. We then used the sort method of the Collections class to sort the list. We also provided a 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 that maintains the element order such as LinkedHashMap as given below.

Output

Note:

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

This example is a part of the Java HashMap tutorial, and Java LinkedHashMap tutorial.

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

About the author

Leave a Reply

Your email address will not be published.