使用比较器 - 降序排序(用户定义的类)排序 [英] Sorting using Comparator- Descending order (User defined classes)
问题描述
我想使用比较器按降序对对象进行排序。
I want to sort my objects in descending order using comparator.
class Person {
private int age;
}
这里我想对Person对象数组进行排序。
Here I want to sort a array of Person objects.
我该怎么做?
推荐答案
你可以这样做降序用户定义的类,这样就覆盖了 compare()方法,
You can do the descending sort of a user-defined class this way overriding the compare() method,
Collections.sort(unsortedList,new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return b.getName().compareTo(a.getName());
}
});
或使用 Collection.reverse()
按 Prince 用户排序降序排序-defined-classes / 18206740#comment33057724_18206740>他的评论。
Or by using Collection.reverse()
to sort descending as user Prince mentioned in his comment.
你可以像这样进行升序排序,
And you can do the ascending sort like this,
Collections.sort(unsortedList,new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
});
用Lambda表达式替换上面的代码(Java 8以上)我们简明扼要:
Replace the above code with a Lambda expression(Java 8 onwards) we get concise:
Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));
从Java 8开始,List有 sort()方法,它采用比较器作为参数(更简洁):
As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :
personList.sort((a,b)->b.getName().compareTo(a.getName()));
这里 a
和 b
被lambda表达式推断为Person类型。
Here a
and b
are inferred as Person type by lambda expression.
这篇关于使用比较器 - 降序排序(用户定义的类)排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!