Sort Map by key in Ascending and descending order by implementing Comparator interface and overriding its compare method and using TreeMap in java


In this Collection framework tutorial we will learn how to sort Map by key  in Ascending and descending order (by implementing Comparator interface and using TreeMap) with lots of examples and programs in java.



Contents of page :
  • Logic to Sort Map by key in Ascending order in java.

  • Example/Program 1 to Sort Map by key in Ascending order by implementing Comparator interface and overriding its compare method in java

  • Example/Program 2 to Sort Map by key in Descending order by implementing Comparator interface and overriding its compare method in java

  • Example/Program 3 to Sort Map by key in Ascending order by using TreeMap, where key is Integer type in java.
  • TreeMap’s putAll method or constructor >

  • Example/Program 4 to Sort Map by key in Ascending order by using TreeMap, where key is customObject/Employee type in java.

  • Example/Program 5 to Sort Map by key in descending order by using TreeMap and implementing Comparator interface, where key is Integer type in java.


Logic to Sort Map by key in Ascending order in java
Implement Comparator interface and override its compare method in java.
Obtain map.entrySet() in set, convert it into list (we have converted set to list because Collections’s sort method can accept only list type as parameter).
Call Collections.sort and pass list [i.e. listOfentrySet] as parameter.
Collections.sort internally calls Arrays.sort,
Arrays.Sort() internally calls Merge Sort.
Merge sort calls overridden compare method of Comparator interface for comparison of keys.
Ultimately listOfentrySet will contain entry (key-value) pairs sorted on basis of keys in java.

Must know fact :
If number of elements is less than 7 then Insertion Sort is used rather than Merge Sort. (because in case elements are less than 7 it offers better time complexity)


Example/Program 1 to Sort Map by key in Ascending order by implementing Comparator interface and overriding its compare method in java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
class SortByKeyAscending implements Comparator<Map.Entry<Integer, Integer>>{
   @Override
   public int compare( Map.Entry<Integer,Integer> entry1, Map.Entry<Integer,Integer> entry2){
       return (entry1.getKey()).compareTo( entry2.getKey() );
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKeyAscendingExample {
   public static void main(String...a){
       Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
       map.put(4, 1);
       map.put(2, 1);
       map.put(3, 1);
       map.put(5, 1);
      
       Set<Entry<Integer, Integer>> entrySet = map.entrySet();
       List<Entry<Integer, Integer>> listOfentrySet = new ArrayList<Entry<Integer, Integer>>(entrySet);
  
       System.out.print("Before sorting by key : ");
       for(Map.Entry<Integer, Integer> entry:listOfentrySet){
        System.out.print(entry.getKey()+"="+entry.getValue()+"  ");
       }
      
       Collections.sort(listOfentrySet, new SortByKeyAscending());
      
       System.out.print("\nAfter sorting by key(ascending): ");
       for(Map.Entry<Integer, Integer> entry:listOfentrySet)
        System.out.print(entry.getKey()+"="+entry.getValue()+"  ");
      
      
   }
}
/*OUTPUT
Before sorting by key : 4=1  2=1  3=1  5=1
After sorting by key(ascending): 2=1  3=1  4=1  5=1
*/
Note : In the above program, only listOfentrySet obtained from map contain entry (key-value) pairs sorted on basis of keys, map is not sorted on basis of keys. We will learn sorting of map in Program 3 and Program 4 below.



Example/Program 2 to Sort Map by key in Descending order by implementing Comparator interface and overriding its compare method in java
In the above program replace SortByKeyAscending class with below SortByKeyDescending class.
class SortByKeyDescending implements Comparator<Map.Entry<Integer, Integer>>{
  @Override
  public int compare( Map.Entry<Integer,Integer> entry1, Map.Entry<Integer,Integer> entry2){
       return (entry2.getKey()).compareTo( entry1.getKey() );
  }
}

OUTPUT will be >
/*OUTPUT
Before sorting by key : 4=1  2=1  3=1  5=1
After sorting by key(descending) : 5=1  4=1  3=1  2=1
*/



Example/Program 3 to Sort Map by key in Ascending order by using TreeMap, where key is Integer type.
TreeMap is sorted by natural order of keys in java.
import java.util.Map;
import java.util.TreeMap;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKeyAscendingExample {
   public static void main(String...a){
       Map<Integer, Integer> treeMap = new TreeMap<Integer, Integer>();
       treeMap.put(4, 1);
       treeMap.put(2, 1);
       treeMap.put(3, 1);
       treeMap.put(5, 1);
       System.out.println("treeMap : "+treeMap);
      
   }
}
/*OUTPUT
treeMap : {2=1, 3=1, 4=1, 5=1}
*/



TreeMap’s putAll method or constructor >

If elements are stored in stored in HashMap or any other collection class that implements Map we can use TreeMap’s putAll method or constructor to sort map on basis of key in java.

Let’s see Example in java >

HashMap -
       Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
       hashMap.put(4, 1);
       hashMap.put(2, 1);
       hashMap.put(3, 1);

TreeMap’s  putAll method -
       Map<Integer, Integer> treeMap = new TreeMap<Integer, Integer>();
       treeMap.putAll(hashMap);

TreeMap’s constructor -
       Map<Integer, Integer> treeMap = new TreeMap<Integer, Integer>(hashMap);


Important Note :
  1. If any class that implements  Map contains null key  - If any class that implements Map contains null key and is converted into TreeMap than NullPointerException (RunTimeException) will be thrown in java.




Example/Program 4 to Sort Map by key in Ascending order by using TreeMap and implementing Comparable interface, where key is customObject/Employee type in java.
TreeMap is sorted by natural order of keys in java.
In program 3 we used Integer as key, Integer class implements Comparable interface and overrides its compareTo() method.
But, for using Employee as key we it must implement Comparable interface and override its compareTo() method in java.

Note : If we Employee don’t implement Comparable interface and override its compareTo() method than ClassCastException (RunTimeException) will be thrown. Because, internally TreeMap calls compare method for comparing keys , while comparing keys casting to java.lang.Comparable will fail at runtime.
import java.util.Map;
import java.util.TreeMap;
class Employee implements Comparable<Employee>{
   String name;
   String id;
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
  
   @Override
   public int compareTo(Employee otherEmployee) {
      //sort Employee on basis of name(ascending order)
      return this.name.compareTo(otherEmployee.name);
   }
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKeyAscendingExample {
   public static void main(String...a){
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");
       Map<Employee, Integer> treeMap = new TreeMap<Employee, Integer>();
       treeMap.put(emp1, 1);
       treeMap.put(emp2, 1);
       treeMap.put(emp3, 1);
       System.out.println("treeMap : "+treeMap);
      
   }
}
/*OUTPUT
treeMap : {Employee{name=amy, id=2}=1, Employee{name=brad, id=1}=1, Employee{name=sam, id=4}=1}
*/




Example/Program 5 to Sort Map by key in descending order by using TreeMap and implementing Comparator interface, where key is Integer type.

TreeMap is sorted by natural order of keys, but we will implement Comparator interface to change the behaviour to sort TreeMap in descending order of keys.
Comparator interface has been used in form of anonymous inner class in java.
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKeyAscendingExample {
   public static void main(String...a){
       Map<Integer,Integer> treeMap = new TreeMap<Integer,Integer>(new Comparator<Integer>(){
                 @Override
                 public int compare(Integer o1, Integer o2) {
                       //using Comparator to sort map in descending order of keys.
                       return o2.compareTo(o1);
                 }
          });
       treeMap.put(4, 1);
       treeMap.put(2, 1);
       treeMap.put(3, 1);
       treeMap.put(5, 1);
      
       System.out.println("treeMap : "+treeMap);
      
   }
}
/*OUTPUT
treeMap : {5=1, 4=1, 3=1, 2=1}

*/

So in this Collection framework tutorial we learned how to sort Map by key  in Ascending and descending order (by implementing Comparator interface and using TreeMap) with lots of examples and programs in java.



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

Collection in java

Collection - List, Set and Map all properties in tabular form

Map hierarchy in java - Detailed - HashMap, Hashtable, ConcurrentHashMap, LinkedHashMap, TreeMap, ConcurrentSkipListMap, IdentityHashMap, WeakHashMap, EnumMap classes



Sorting Collection by implementing comparator and Comparable, using TreeMap and TreeSet, Collections.sort and Arrays.sort >

Comparable vs Comparator - differences and sorting list by implementing Comparable and Comparator in classes and inner classes


Arrays.sort to sort arrays by implementing Comparator and how Comparator of superclass can be used by subclasses


Sort Set by using TreeSet and by implementing Comparator and Comparable interface


Sort Map by value in Ascending and descending order by implementing Comparator interface and overriding its compare method





eEdit
Must read for you :