Java TreeMap 升序|降序排列

  1. import java.util.Comparator;  
  2. import java.util.TreeMap;  
  3. public class Main {  
  4.     public static void main(String[] args) {  
  5.         TreeMap<Integer,Integer> map1 = new TreeMap<Integer,Integer>();  //默认的TreeMap升序排列  
  6.         TreeMap<Integer,Integer> map2= new TreeMap<Integer,Integer>(new Comparator<Integer>(){  
  7.              /*  
  8.              * int compare(Object o1, Object o2) 返回一个基本类型的整型,  
  9.              * 返回负数表示:o1 小于o2,  
  10.              * 返回0 表示:o1和o2相等,  
  11.              * 返回正数表示:o1大于o2。  
  12.              */    
  13.             public int 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. }  

猜你喜欢

转载自stunizhengjia.iteye.com/blog/2403919