Skip to content

Java Sort HashMap by Key Example

Java sort HashMap by key example shows how to sort HashMap by key in Java using the TreeMap class and a Comparator.

How to Sort HashMap by Key in Java?

The HashMap is meant for quick look-ups and may not maintain the order of the inserted elements. However, retrieving the values based on sorted keys is possible in below given ways.

Using TreeMap

If you have a requirement to access the HashMap values by the sorted keys, you should use the TreeMap class instead. If you already have a HashMap object, you can convert the HashMap to a TreeMap object, thus sorting it by the keys automatically as given in the below example.

Output

Now let’s try to put custom class objects as the key instead of Integer objects. We are going to store the employee and manager relation mappings using the Employee class objects in the below given example.

Output

Well, we encountered the ClassCastException exception. What went wrong? The first example worked because we used Integer objects as keys and Integer class implements the Comparable interface (so that Integer objects can be compared to one another while being sorted).

If you want to use your custom class objects as key, either the class needs to implement the Comparable interface or you need to provide a custom comparator before the object can be sorted by the TreeMap.

Below given example uses a custom Comparator to compare Employee objects and sorts them based on the employee name.

Output

Finally, you can change below given line,

to this line,

and remove the the EmpComparator class definition to use an anonymous Comparator.

Please also check out How to sort HashMap by values example.

This example is a part of the Java HashMap 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.