欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-16 16:08:10
1 //传入一个Map 返回它按value排序后的结果 sort为正序还是倒序(-1倒序),size为要几条数据 2 private static Map sortMapByValues(Map aMap, int sort, int size) { 3 4 Set> mapEntries = aM... ......
 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     }