Java TreeMap Ascending | Descending

  1. import  java.util.Comparator;  
  2. import  java.util.TreeMap;  
  3. public class  Main {   
  4.     publicstaticvoid main(String[] args) {    
  5.         TreeMap<Integer,Integer> map1 =  new  TreeMap<Integer,Integer>();   //The default TreeMap is sorted in ascending order  
  6.         TreeMap<Integer,Integer> map2= new TreeMap<Integer,Integer>(new Comparator<Integer>(){  
  7.              /*  
  8.              * int compare(Object o1, Object o2) returns a primitive integer,  
  9.              * Return a negative number to indicate: o1 is less than o2,  
  10.              * Return 0 means: o1 and o2 are equal,  
  11.              * Returns a positive number indicating: o1 is greater than o2.  
  12.              */    
  13.             publicint compare(Integer a,Integer b){   
  14.                 return b-a;           
  15.             }  
  16.             });  
  17.         map2.put(1,2);  
  18.         map2.put(2,4);  
  19.         map2.put(71);  
  20.         map2.put(5,2);  
  21.         System.out.println("Map2="+map2);    
  22.           
  23.         map1.put(1,2);  
  24.         map1.put(2,4);  
  25.         map1.put(71);  
  26.         map1.put(5,2);  
  27.         System.out.println("map1="+map1);  
  28.     }  
  29.       
  30.       
  31.       
  32.       
  33. }  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326463670&siteId=291194637