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

 1    //传入一个Map  返回它按value排序后的结果 sort为正序还是倒序(-1倒序),size为要几条数据
 2     private static Map sortMapByValues(Map aMap, int sort, int size) {
 3 
 4         Set> mapEntries = aMap.entrySet();
 5 
 6         List> aList = new LinkedList>(mapEntries);
 7 
 8         Collections.sort(aList, new Comparator>() {
 9 
10             @Override
11             public int compare(Map.Entry ele1,
12                                Map.Entry 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 aMap2 = new LinkedHashMap();
21         for (Map.Entry entry : aList) {
22             aMap2.put(entry.getKey(), entry.getValue());
23             if (aMap2.size() == size) {
24                 break;
25             }
26         }
27         return aMap2;
28     }

 

你可能感兴趣的:(传入一个Map 返回它按value排序后的结果)