按照value排序(倒序),取前N位
----------------------------------------------------------------------------------------------------
public class RelationSpanSorter {
private RelationSpanSorter() {
}
// test
public static void main(String[] args) {
Map map = new HashMap();
map.put(1, 4);
map.put(5, 1);
map.put(2, 3);
map.put(4, 2);
map.put(12, 12);
map.put(21, 21);
map.put(11, 11);
map.put(41, 41);
map.put(31, 31);
map.put(15, 15);
map.put(62, 62);
map.put(14, 14);
map.put(111, 111);
map.put(523, 523);
map.put(92, 92);
map.put(40, 40);
Map sorted = sortByValue(map, 8);
System.out.println(sorted);
}
@SuppressWarnings("unchecked")
public static Map sortByValue(Map map, int topN) {
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return -((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
}
});
Map result = new LinkedHashMap();
int i = 0;
for (Object it : list) {
Map.Entry entry = (Map.Entry) it;
if (i >= topN) {
break;
}
result.put(entry.getKey(), entry.getValue());
i++;
}
return result;
}
}
=======================================

本文介绍了如何使用Java对Map按value进行排序,包括倒序排列并取前N位的方法。提供了两种不同的实现方式,一种是通过自定义Comparator排序并用LinkedHashMap保存结果,另一种是利用TreeSet的特性实现排序。代码示例详细展示了具体的实现步骤。
最低0.47元/天 解锁文章
1619

被折叠的 条评论
为什么被折叠?



