Collections

Java Sort HashMap by Key Example

Java sort HashMap by Key Example shows how to sort HashMap by key in Java. This example also shows how to sort HashMap by key using TreeMap and a Comparator.

How to Sort HashMap by Key in Java?

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

Sort HashMap by key using TreeMap

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

Output

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

Output

Well, we encountered ClassCastException. What went wrong? The first example worked because we used Integer objects as keys and Integer class implements 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 Comparable interface or you need to provide a custom comparator before the object can be sorted by 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 EmpComparator class definition to use anonymous Comparator.

Also see: How to sort HashMap by values

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.