TreeMap’s putAll method to sort map on basis of key




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.



Let’s see Example >

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);

Full program >
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKey {
   public static void main(String...a){
       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);
       System.out.println("treeMap : "+treeMap);
           
   }
}
/*OUTPUT
treeMap : {2=1, 3=1, 4=1}
*/


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.



RELATED LINKS>


Program to sort Integer array using Arrays.sort (by default Arrays.sort will sort array in ascending order)


eEdit
Must read for you :