Program to Sort Map by key in Ascending order by using TreeMap, where key is Integer type.













TreeMap is sorted by natural order of keys.

import java.util.Map;
import java.util.TreeMap;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKeyAscending {
   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}
*/

No comments:

Post a Comment