传入一个Map 返回它按value排序后的结果

2019-08-09 00:00:00 返回 排序 传入
 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     }

 

相关文章