Monday, June 28, 2021

2 Ways to sort HashMap in Java? 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 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 remains is to get the keys, sort them and then process data 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. HashMap, and 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.




2 Ways to sort HashMap in Java

two ways to sort Map in JavaHere 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. 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);
        Collections.sort(sortedIds);
        System.out.println("sorted keys of map : " + sortedIds);
    }

}

Output:
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 Map in Java. We have learned two ways to sort 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. Both approaches have their pros and cons and you should use TreeMap if sorting and ordering of keys is a requirement. 

If 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 e.g. HashMap, and only sort them when needed using Collections.sort() method.


1 comment:

  1. How I can sort without using treeset?

    ReplyDelete

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