How to Sort HashMap in Java

HashMap in Java calculates hash based on the key of the inserted (key, value) pair and store its elements according to that. So essentially HashMap is an unordered collection but you may come across a scenario when you want to sort HashMap in Java.

Sorting on HashMap can be done on either key or value, in this post we’ll see ways to sort HashMap in Java based on its keys or on its values.

Sorting HashMap on keys

If you have to sort HashMap on keys in Java, simplest option is to convert your HashMap to a TreeMap.

TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. If you want to sort HashMap according to the natural ordering of its keys you can use the following constructor of the TreeMap class.

TreeMap(Map<? extends K,? extends V> m)– Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.

Example code

Output

Sorting HashMap on Values

For sorting HashMap on values you will have to convert HashMap to a Set and then sort that Set. For sorting a Set you have again two options convert that set to List or to a TreeSet.

If you just want the values of the Map in the sorted order then converting the values of the Map to a TreeSet is the simplest option.

Output

As you can see the values are sorted, only drawback is now you have a Set instead of a Map as you have only values stored now.

If you want a Map as end result of sorting a HashMap in Java then the process is a bit lengthy.

  1. Create a TreeSet specifying a Comparator for sorting.
  2. Convert the entry set of HashMap to a TreeSet by using addAll() method. At this step you have a sorted set containing the Map.entry elements.
  3. Create a LinkedHashMap to store the sorted values. LinkedHashMap is used here because it maintains insertion order.
  4. Iterate the TreeSet and put values in the created LinkedHashMap.

Example Java code

Output

Rather than TreeSet you can also use an ArrayList to store Map.Entry elements. In that case you can use Collections.sort(list, new EmpComparator()) to sort on values.

That’s all for the topic How to Sort HashMap in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.