Passing a Map <String, Long> returns its result by value after ordering

1     // pass a Map <String, Long> return its value according to the result of the sort order of positive or descending order (reverse -1), size of the data to several 
2      Private  static Map <String, Long> sortMapByValues (the Map <String, Long> amap, int Sort, int size) {
 . 3  
. 4          the Set <of Map.Entry <String, Long >> mapEntries = aMap.entrySet ();
 . 5  
. 6          List <of Map.Entry <String, Long >> of aList = new new the LinkedList <of Map.Entry <String, Long >> (mapEntries);
 . 7  
. 8          the Collections.sort (of aList, new new Comparator <of 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     }

 

Guess you like

Origin www.cnblogs.com/ysyy/p/11200537.html
Recommended