Java TreeMap分别对key和value降序排列

TreeMap默认按key进行升序排序,下面我们将对key和value进行降序排列。

1. key进行降序排序

Map<String,String> map = new TreeMap<String,String>(new Comparator<String>(){ 
   public int compare(String obj1,String obj2){ 
    //降序排序 
    return obj2.compareTo(obj1); 
   } 
}); 
map.put("month", "The month"); 
map.put("bread", "The bread"); 
map.put("attack", "The attack"); 
Set<String> keySet = map.keySet(); 
Iterator<String> iter = keySet.iterator(); 
while(iter.hasNext()){ 
    String key = iter.next(); 
    System.out.println(key+":"+map.get(key)); 
}

2. value进行降序排列

List<Map.Entry<String,String>> mappingList = null; 
Map<String,String> map = new TreeMap<String,String>(); 
map.put("aaaa", "month"); 
map.put("bbbb", "bread"); 
map.put("ccccc", "attack"); 
//通过ArrayList构造函数把map.entrySet()转换成list 
mappingList = new ArrayList<Map.Entry<String,String>>(map.entrySet()); 
//通过比较器实现比较排序 
Collections.sort(mappingList, new Comparator<Map.Entry<String,String>>(){ 
  public int compare(Map.Entry<String,String> mapping1,Map.Entry<String,String> mapping2){  
      return mapping1.getValue().compareTo(mapping2.getValue()); 
  }
});
for(Map.Entry<String,String> mapping:mappingList){  
    System.out.println(mapping.getKey()+":"+mapping.getValue()); 
}

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。