Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

2 Ways to sort a Map in Java by Keys? TreeMap and HashMap Example

So you have a Map in your Java program and you want to process its data in sorted order. Since Map doesn't guarantee any order for its keys and values, you always end up with unsorted keys and Map. If you really need a sorted Map then think about using the TreeMap, which keeps all keys in sorted order. This could be either natural order of keys (defined by Comparable) or custom order (defined by Comparator), which you can provide while creating an instance of TreeMap. If you don't have your data in a sorted Map then the only option that remain for you is to get the keys and values, sort them and then process your Map in that order. 

Since keys are unique in Map, it returns a set of keys, which means you cannot sort them by using Collections.sort() method, which accepts a List. So what to do? Well, we can convert our Set into List as shown in this example, then sort them using the sort() method in any order and process them accordingly.

Now, which approach is better, either using TreeMap or keeping mappings in an unsorted general-purpose Map implementation like HashMap or Hashtable? well, both have their advantages and disadvantages, but if required is always keep keys in sorted order then use TreeMap, though insertions will be slow keys will always remain in sorted order.

On the other hand, if the requirement is just to process data in a particular order, which also varies depending upon which method is using Map, then use general-purpose Map e.g. HashMapand only sort when needed. Insertion will be much faster, but it will require additional time to sort keys before processing.

In the next section, we will see examples of both approaches of sorting maps in Java. By the way, you can also process map by sorting values, that's another option available depending upon your requirement but be mindful that values can be duplicate in a Map in Java. 

2 Ways to Sort a Map in Java? TreeMap and ArrayList

Here is Java program to sort Map on keys. This program first creates a HashMap with key type Integer and value type String, then adds few elements, which is actually mapping of id to name. Now task is to process elements in increasing order of id, to achieve this we either need to sort Map on ids, or only sort keys of Map before processing. 

How to sort a Map by keys in Java? TreeMap and HashMap Example

By the way, these examples sort map on keys only, if you want to sort map on values, see this article.

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

 * Java Program of sorting Map by keys in Java. 
 * You can use this technique to sort HashMap, 
 * Hashtable, ConcurrentHashMap, LinkedHashMap or 
 * any arbitrary implementation of Map interface in Java.
 * @author Javin Paul
public class MapSorterDemo{

    public static void main(String args[]) {
        // Unsorted Integer to String Map
        Map<Integer, String> idToName = new HashMap<>();
        idToName.put(1001, "Joe");
        idToName.put(1003, "Kevin");
        idToName.put(1002, "Peter");
        idToName.put(1005, "Johnson");
        idToName.put(1004, "Ian");

        System.out.println("unsorted map : " + idToName);

        // Sorting Map by keys
        TreeMap<Integer, String> sorted = new TreeMap<>(idToName);
        System.out.println("sorted map : " + sorted);

        // If you want to process Map in sorted order of keys
        // then you can keep an unsorted Map, but take the
        // keyset and sort them, before processing
        Set<Integer> ids = idToName.keySet();
        System.out.println("unsorted keys of map : " + ids);
        List<Integer> sortedIds = new ArrayList<>(ids);
        System.out.println("sorted keys of map : " + sortedIds);


unsorted map : {1001=Joe, 1003=Kevin, 1002=Peter, 1005=Johnson, 1004=Ian}
sorted map : {1001=Joe, 1002=Peter, 1003=Kevin, 1004=Ian, 1005=Johnson}
unsorted keys of map : [1001, 1003, 1002, 1005, 1004]
sorted keys of map : [1001, 1002, 1003, 1004, 1005]

That's all about how to sort a Map in Java by keys. You have learned two ways to sort a Map by keys, first by using TreeMap, which requires copying the content of the original map and create a sorted map, second, by only sorting keys in Java. 

Both approaches have their pros and cons and you should use TreeMap if sorting and ordering of keys is a requirement. 

two ways to sort Map in JavaIf your business logic requires you to process mapping in a different order at different times, then you can still keep data in general-purpose Map implementation like HashMap, and only sort them when needed using Collections.sort() method.

Thanks for reading this article if you find this sorted and unsorted Map Example in Java useful then please share them with your friends and colleagues. If you have any questions or feedback then please drop me a note. 


Feel free to comment, ask questions if you have any doubt.