How to Sort HashMap in Java
Java HashMap does not preserve any order by default. If there is a need to sort HashMap we sort it explicitly based on the requirements. Java provides an option to sort HashMap based on keys and values. In this section, we will learn how to sort HashMap according to keys and values.
- Sort HashMap by Keys
- Sort HashMap by Values
Sort HashMap by Keys
There are following ways to sort HashMap by keys:
- By using TreeMap
- By using LinkedHashMap
When we use LinkedHashMap, we should follow the process:
When we use LinkedHashMap, then we need to get Key set. Convert the Set into List, sort the list and then add the sorted list into LinkedHashMap in the same order. The same process we have done in the example Sort HashMap by Value.
Example of sorting HashMap by Keys
In the following example, we use TreeMap constructor to sort the elements and pass the object of HashMap class as an argument. This is the simplest way to sort HashMap by Keys.
Output:
Before Sorting Roll no: 17 name: Arun Roll no: 23 name: Yash Roll no: 9 name: Neelesh Roll no: 15 name: Swarit After Sorting Roll no: 9 name: Neelesh Roll no: 15 name: Swarit Roll no: 17 name: Arun Roll no: 23 name: Yash
Sort HashMap by Values using Comparator Interface
In Java, sorting HashMap by values is complicated because there is no direct method is available. To sort the HashMap by values, we need to create a Comparator. It compares two elements based on the values.
After that get the Set of elements from the Map and convert Set into the List. Use the Collections.sort(List) method to sort the list of elements by values by passing customized comparator. Now create a new LinkedHashMap and copy the sorted elements into that. Since LinkedHashMap guarantees the insertion order of mappings. We get a HashMap whose values are in sorted order.
There is a slight difference between sorting HashMap by Keys and Values is that it can have duplicate values but not duplicate Keys. We cannot use TreeMap to sort values because TreeMap sorts elements by Keys.
Example of sort HashMap by values
Output:
Before Sorting: Roll no: 1 Name: Ritesh Roll no: 67 Name: Boby Roll no: 5 Name: Zoya Roll no: 6 Name: Tushar Roll no: 10 Name: Praveen Roll no: 12 Name: Ashu Roll no: 78 Name: Yash After Sorting: Roll no: 12 Name: Ashu Roll no: 67 Name: Boby Roll no: 10 Name: Praveen Roll no: 1 Name: Ritesh Roll no: 6 Name: Tushar Roll no: 78 Name: Yash Roll no: 5 Name: Zoya