java对象下的变量排序,按对象变量对对象的LinkedList进行排序

Here is my problem, I have a LinkedList of objects, which have a String name and an int score value.

Now, I need to sort this list in descending order based on the score value.

How do I do that? I tried with Collections.sort(List), but that doesn't work with objects.

How do I tell Java to use the score as the value to comparison?

解决方案

The Collections.sort method accepts a comparator as its second argument.

You can pass in a comparator that defines the ordering that you want.

For example given a Person class:

class Person {

private final String name;

private final int score;

Person(String name, int score) {

this.name = name;

this.score = score;

}

@Override

public String toString() {

return "Person{" +

"name='" + name + '\'' +

", score=" + score +

'}';

}

}

You can use Collections.sort with a custom comparator to sort Persons by descending order of score like this:

List list = new LinkedList<>(Arrays.asList(new Person("Jack", 3), new Person("Mike", 9)));

System.out.println("before: " + list);

Collections.sort(list, new Comparator() {

@Override

public int compare(Person o1, Person o2) {

return o2.score - o1.score;

}

});

System.out.println("after: " + list);

This will output:

before: [Person{name='Jack', score=3}, Person{name='Mike', score=9}]

after: [Person{name='Mike', score=9}, Person{name='Jack', score=3}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值