top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

I need Two Ways to sort HashMap in Java? Can someone share it with example?

+1 vote
375 views
I need Two Ways to sort HashMap in Java? Can someone share it with example?
posted Nov 2, 2015 by Shyam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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 a sorted order. This could be either natural order of keys (defined by Comparable) or a custom order (defined by Comparator), which you can provide, while creating instance of TreeMap. If you don't have your data in a sorted Map then only option 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 accept a List. So what to do? Well, we can convert our Set into List as shown in this example, then sort them using 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 requirement is always keep keys in sorted order then use TreeMap, though insertions will be slow but keys will always remain in sorted order. On the other hand, if 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 next section, we will see example of both approach of sorting Map 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 create an 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 element 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 sorts 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.
 */
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 to copy content of original map and create a sorted map, second, by only sorting keys. Both approach has their pros and cons and you should use TreeMap, if sorting and ordering of key is a requirement. If your business logic require you to process mapping in different order at different time, then you can still keep data in general purpose Map implementation e.g. HashMap and only sort them when needed using Collections.sort() method.

answer Nov 3, 2015 by Karthick.c
...