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

Map集合按照value和key进行排序

时间:2017-04-14 23:10:55      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:ati   compareto   排序算法   div   blog   工作   entry   排序   .com   

最近由于特殊的业务需求,需要做相关数据排序,下面就贴出其中的将map集合中按照value或者key进行排序的代码,后面再具体详说。

 1 /**
 2      * map 集合排序
 3      * @param map
 4      * @return
 5      */
 6     public static <K, V extends Comparable<? super V>> Map<K, V> sortMap(Map<K, V> map) 
 7     {
 8         List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
 9         Collections.sort(list, new Comparator<Map.Entry<K, V>>() 
10         {
11             public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) 
12             {
13                 // 按照 value进行排序
14                 return (o2.getValue()).compareTo(o1.getValue());  // 20 ,3,1 倒叙
15 //                return (o1.getValue()).compareTo(o2.getValue());  // 1 ,3,20 正序
16                 // 按照key 进行排序
17 //                return ((String) o1.getKey()).compareTo((String) o2.getKey());  // k1 ,k2,k3 正序
18 //                return ((String) o2.getKey()).compareTo((String) o1.getKey());  // k3 ,k2,k1  倒叙
19             }
20         });
21 
22         Map<K, V> result = new LinkedHashMap<K, V>();
23         for (Map.Entry<K, V> entry : list) 
24         {
25             result.put(entry.getKey(), entry.getValue());
26         }
27         return result;
28     }

后面补充在工作中,由于公司业务,做的一个实际的排序算法。

Map集合按照value和key进行排序

标签:ati   compareto   排序算法   div   blog   工作   entry   排序   .com   

原文地址:http://www.cnblogs.com/yangh965/p/6711189.html

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