java按照map的value排序

来源:互联网 发布:国际域名和国内域名 编辑:程序博客网 时间:2024/05/18 01:49
java的TreeMap可以排序,只可惜是按照key来排序的,或者重写其他Map的排序算法也都是按照key来排序的,下面贴出来一个按照value排序的算法:

 

[java] view plaincopy
  1. public class SortMap {  
  2.     public static void main(String[] args) throws Exception {  
  3.         // TODO code application logic here  
  4.         Map<String, Integer> myMap = new LinkedHashMap();  
  5.         myMap.put("1"1);  
  6.         myMap.put("2"4);  
  7.         myMap.put("3"3);  
  8.         myMap.put("4"9);  
  9.         myMap.put("5"6);  
  10.         myMap.put("6"2);  
  11.           
  12.         printMap(myMap);  
  13.           
  14.         myMap = sortMap(myMap);  
  15.           
  16.         printMap(myMap);  
  17.     }  
  18.       
  19.     private static void printMap(Map map){  
  20.         System.out.println("===================mapStart==================");  
  21.         Iterator it = map.entrySet().iterator();  
  22.         while(it.hasNext()){  
  23.             Map.Entry entry = (Map.Entry) it.next();  
  24.             System.out.println(entry.getKey() + ":" + entry.getValue());  
  25.         }  
  26.         System.out.println("===================mapEnd==================");  
  27.     }   
  28.   
  29.     public static Map sortMap(Map oldMap) {  
  30.         ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());  
  31.         Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {  
  32.   
  33.             @Override  
  34.             public int compare(Entry<java.lang.String, Integer> arg0,  
  35.                     Entry<java.lang.String, Integer> arg1) {  
  36.                 return arg0.getValue() - arg1.getValue();  
  37.             }  
  38.         });  
  39.         Map newMap = new LinkedHashMap();  
  40.         for (int i = 0; i < list.size(); i++) {  
  41.             newMap.put(list.get(i).getKey(), list.get(i).getValue());  
  42.         }  
  43.         return newMap;  
  44.     }  
  45. }  

0 0
原创粉丝点击