按对象变量对对象的LinkedList进行排序 [英] Sort a LinkedList of objects by object's variable
问题描述
这是我的问题,我有一个LinkedList
对象,这些对象具有String
名称和int
得分值.
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.
我该怎么做?我尝试使用Collections.sort(List)
,但这不适用于对象.
How do I do that? I tried with Collections.sort(List)
, but that doesn't work with objects.
如何告诉Java将分数用作比较的值?
How do I tell Java to use the score as the value to comparison?
推荐答案
Collections.sort
方法接受比较器作为第二个参数.
您可以传入定义所需顺序的比较器.
例如,给定一个Person
类:
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 +
'}';
}
}
您可以将Collections.sort
与自定义比较器结合使用,按分数的降序对人员进行排序,如下所示:
You can use Collections.sort
with a custom comparator to sort Persons by descending order of score like this:
List<Person> list = new LinkedList<>(Arrays.asList(new Person("Jack", 3), new Person("Mike", 9)));
System.out.println("before: " + list);
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o2.score - o1.score;
}
});
System.out.println("after: " + list);
这将输出:
before: [Person{name='Jack', score=3}, Person{name='Mike', score=9}]
after: [Person{name='Mike', score=9}, Person{name='Jack', score=3}]
这篇关于按对象变量对对象的LinkedList进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!