Sort Hashmap in Java with examples

The purpose of HashMap isn’t to keep entries in a sorted order, but Java provides you the option to sort HashMap on the basis of values or keys.
To sort HashMap based on keys, all that is needed is creating a TreeMap by copying entries from the desired HashMap. One can implement SortedMap by TreeMap and the keys can be kept in their normal order or any custom order that you may specify by using Comparator provided during the creation of TreeMap.This means that the entries of HashMap can be processed in a sorted order but a HashMap containing mappings cannot be passed in a specified order. HashMap does not guarantee any kind of ordering.Sorting HashMap on the basis of values is quite a complex process because there isn’t any direct method to perform that operation.

To sort Hashmap by keys

There are 2 methods to sort HashMap by keys. First is by using TreeMap. The second method is to use LinkedHashMap. To sort entries using TreeMap, all that is required is for you is to create a TreeMap and copy the content of Hashmap to it. If you are using LinkedHashMap, then you must have a key set. Then you must convert that set to a List. Add the entries into the LinkedHashMap while keeping the order same. Note that HashMap can have 1 null key but there cannot be any duplicate keys

Program to Sort HashMap by Keys


To sort Hashmap by values

  1. Create a Comparator that can compare 2 entries based on their values.
  2. Get the Set of inputs from the Map.
  3. Convert the Set to List and then use the method Collections.sort(List) to sort the list of entries based on values by passing the customized value comparator. It is equivalent to sorting an ArrayList in Java.
  4. Create a LinkedHashMap and transfer all the sorted entries into it.
  5. Since there is a guarantee of insertion order of mappings while using LinkedHashMap, we get a Map where the contents are sorted on the basis of values.

Program to Sort HashMap by Values


Leave a Reply