设为首页 加入收藏

TOP

传入一个Map<String,Long> 返回它按value排序后的结果
2019-09-17 18:22:32 】 浏览:28
Tags:传入 一个 Map< String Long> 返回 value 排序 后的 结果
 1    //传入一个Map<String,Long>  返回它按value排序后的结果 sort为正序还是倒序(-1倒序),size为要几条数据
 2     private static Map<String, Long> sortMapByValues(Map<String, Long> aMap, int sort, int size) {
 3 
 4         Set<Map.Entry<String, Long>> mapEntries = aMap.entrySet();
 5 
 6         List<Map.Entry<String, Long>> aList = new LinkedList<Map.Entry<String, Long>>(mapEntries);
 7 
 8         Collections.sort(aList, new Comparator<Map.Entry<String, Long>>() {
 9 
10             @Override
11             public int compare(Map.Entry<String, Long> ele1,
12                                Map.Entry<String, Long> ele2) {
13                 if (sort < 0) {
14                     return ele2.getValue().compareTo(ele1.getValue());
15                 }
16                 return ele1.getValue().compareTo(ele2.getValue());
17             }
18         });
19         // Storing the list into Linked HashMap to preserve the order of insertion.
20         Map<String, Long> aMap2 = new LinkedHashMap<String, Long>();
21         for (Map.Entry<String, Long> entry : aList) {
22             aMap2.put(entry.getKey(), entry.getValue());
23             if (aMap2.size() == size) {
24                 break;
25             }
26         }
27         return aMap2;
28     }

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Struts2 入门 下一篇MyBatis从入门到精通(第1章):MyB..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目