//传入一个Map<String,Long> 返回它按value排序后的结果 sort为正序还是倒序(-1倒序),size为要几条数据
private static Map<String, Long> sortMapByValues(Map<String, Long> aMap, int sort, int size) {
Set<Map.Entry<String, Long>> mapEntries = aMap.entrySet();
List<Map.Entry<String, Long>> aList = new LinkedList<Map.Entry<String, Long>>(mapEntries);
Collections.sort(aList, new Comparator<Map.Entry<String, Long>>() {
@Override
public int compare(Map.Entry<String, Long> ele1,
Map.Entry<String, Long> ele2) {
if (sort < 0) {
return ele2.getValue().compareTo(ele1.getValue());
}
return ele1.getValue().compareTo(ele2.getValue());
}
});
// Storing the list into Linked HashMap to preserve the order of insertion.
Map<String, Long> aMap2 = new LinkedHashMap<String, Long>();
for (Map.Entry<String, Long> entry : aList) {
aMap2.put(entry.getKey(), entry.getValue());
if (aMap2.size() == size) {
break;
}
}
return aMap2;
}
传入一个Map<String,Long> 返回它按value排序后的结果
最新推荐文章于 2023-04-23 08:45:03 发布