java map sort_Map 按值排序 (Map sort by value) – Java | 学步园

本文介绍了如何使用Java对Map按value进行排序,包括倒序排列并取前N位的方法。提供了两种不同的实现方式,一种是通过自定义Comparator排序并用LinkedHashMap保存结果,另一种是利用TreeSet的特性实现排序。代码示例详细展示了具体的实现步骤。
摘要由CSDN通过智能技术生成

按照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;

}

}

=======================================

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值