傳入一個Map 返回它按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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM