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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

}

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

以上代码改编自:http://blog.csdn.net/srjklssj/article/details/6324880

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

Map是键值对的集合,又叫作字典或关联数组等,是最常见的数据结构之一。在java如何让一个map按value排序呢? 看似简单,但却不容易!

比如,Map中key是String类型,表示一个单词,而value是int型,表示该单词出现的次数,现在我们想要按照单词出现的次数来排序:

Map map = new TreeMap();

map.put("me", 1000);

map.put("and", 4000);

map.put("you", 3000);

map.put("food", 10000);

map.put("hungry", 5000);

map.put("later", 6000);

按值排序的结果应该是:

key value

me 1000

you 3000

and 4000

hungry 5000

later 6000

food 10000

首先,不能采用SortedMap结构,因为SortedMap是按键排序的Map,而不是按值排序的Map,我们要的是按值排序的Map。

Couldn't you do this with a SortedMap?

No, because the map are being sorted by its keys.

方法一:

如下Java代码:

importjava.util.Iterator;

importjava.util.Set;

importjava.util.TreeSet;

public classMain{

public static void main(String[]args) {

Setset= new TreeSet();set.add(new Pair("me", "1000"));set.add(new Pair("and", "4000"));set.add(new Pair("you", "3000"));set.add(new Pair("food", "10000"));set.add(new Pair("hungry", "5000"));set.add(new Pair("later", "6000"));set.add(new Pair("myself", "1000"));

for (Iteratori=set.iterator();i.hasNext();)

System.out.println(i.next());

}

}

classPairimplements Comparable {

private final Stringname;

private final intnumber;

public Pair(Stringname, intnumber) {

this.name=name;

this.number=number;

}

public Pair(Stringname, Stringnumber) throws NumberFormatException {

this.name=name;

this.number= Integer.parseInt(number);

}

public int compareTo(Objecto) {

if (oinstanceofPair) {

intcmp= Double.compare(number, ((Pair)o).number);

if (cmp!= 0) {

returncmp;

}

returnname.compareTo(((Pair)o).name);

}

throw new ClassCastException("Cannot compare Pair with "

+o.getClass().getName());

}

public String toString() {

returnname+ ' ' +number;

}

}

类似的C++代码:

typedef pair PAIR;

int cmp(const PAIR& x, const PAIR& y)

{

return x.second > y.second;

}

map m;

vector vec;

for (map::iterator curr = m.begin(); curr != m.end(); ++curr)

{

vec.push_back(make_pair(curr->first, curr->second));

}

sort(vec.begin(), vec.end(), cmp);

上面方法的实质意义是:将Map结构中的键值对(Map.Entry)封装成一个自定义的类(结构),或者直接用Map.Entry类。自定义类知道自己应该如何排序,也就是按值排序,具体为自己实现Comparable接口或构造一个Comparator对象,然后不用Map结构而采用有序集合(SortedSet,

TreeSet是SortedSet的一种实现),这样就实现了Map中sort by value要达到的目的。就是说,不用Map,而是把Map.Entry当作一个对象,这样问题变为实现一个该对象的有序集合或对该对象的集合做排序。既可以用SortedSet,这样插入完成后自然就是有序的了,又或者用一个List或数组,然后再对其做排序(Collections.sort()

or Arrays.sort())。

Encapsulate the information in its own class. Either implement

Comparable and write rules for the natural ordering or write a

Comparator based on your criteria. Store the information in a sorted

collection, or use the Collections.sort() method.

方法二:

You can also use the following code to sort by value:

public static Map sortByValue(Mapmap)

{

Listlist= new LinkedList(map.entrySet());

Collections.sort(list, new Comparator() {

public int compare(Objecto1, Objecto2) {

return ((Comparable) ((Map.Entry) (o1)).getValue())

.compareTo(((Map.Entry) (o2)).getValue());

}

});

Mapresult= new LinkedHashMap();

for (Iteratorit=list.iterator();it.hasNext();) {

Map.Entry entry= (Map.Entry)it.next();result.put(entry.getKey(),entry.getValue());

}

returnresult;

}

public static Map sortByValue(Mapmap, final booleanreverse) {

Listlist= new LinkedList(map.entrySet());

Collections.sort(list, new Comparator() {

public int compare(Objecto1, Objecto2) {

if (reverse) {

return -((Comparable) ((Map.Entry) (o1)).getValue())

.compareTo(((Map.Entry) (o2)).getValue());

}

return ((Comparable) ((Map.Entry) (o1)).getValue())

.compareTo(((Map.Entry) (o2)).getValue());

}

});

Mapresult= new LinkedHashMap();

for (Iteratorit=list.iterator();it.hasNext();) {

Map.Entry entry= (Map.Entry)it.next();result.put(entry.getKey(),entry.getValue());

}

returnresult;

}

Mapmap= new HashMap();map.put("a", 4);map.put("b", 1);map.put("c", 3);map.put("d", 2);

Mapsorted= sortByValue(map);

System.out.println(sorted);

// output : {b=1, d=2, c=3, a=4}

或者还可以这样:

Mapmap= new HashMap();map.put("a", 4);map.put("b", 1);map.put("c", 3);map.put("d", 2);

Set>treeSet= new TreeSet>(

new Comparator>() {

public int compare(Map.Entryo1,

Map.Entryo2) {

Integerd1=o1.getValue();

Integerd2=o2.getValue();

intr=d2.compareTo(d1);

if (r!= 0)

returnr;

else

returno2.getKey().compareTo(o1.getKey());

}

});treeSet.addAll(map.entrySet());

System.out.println(treeSet);

// output : [a=4, c=3, d=2, b=1]

另外,Groovy 中实现 sort map by value,当然本质是一样的,但却很简洁 :

用 groovy 中 map 的 sort 方法(需要 groovy 1.6),

def result = map.sort(){ a, b ->

b.value.compareTo(a.value)

}

如:

["a":3,"b":1,"c":4,"d":2].sort{ a,b -> a.value - b.value }

结果为: [b:1, d:2, a:3, c:4]

Python中也类似:

h = {"a":2,"b":1,"c":3}

i = h.items() // i = [('a', 2), ('c', 3), ('b', 1)]

i.sort(lambda (k1,v1),(k2,v2): cmp(v2,v1) ) // i = [('c', 3), ('a', 2), ('b', 1)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值