码迷,mamicode.com
首页 > 编程语言 > 详细

java按照map的value排序 转载http://blog.csdn.net/tsingheng/article/details/7909861

时间:2016-01-03 00:30:42      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

java的TreeMap可以排序,只可惜是按照key来排序的,或者重写其他Map的排序算法也都是按照key来排序的,下面贴出来一个按照value排序的算法:

 

  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. }  

技术分享

java按照map的value排序 转载http://blog.csdn.net/tsingheng/article/details/7909861

标签:

原文地址:http://www.cnblogs.com/1130136248wlxk/p/5095447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!