使用比较器进行排序 - 降序(用户定义的类)[已关闭]
2022-08-31 11:56:21
我想使用比较器按降序对对象进行排序。
class Person {
private int age;
}
在这里,我想对 Person 对象的数组进行排序。
我该怎么做?
我想使用比较器按降序对对象进行排序。
class Person {
private int age;
}
在这里,我想对 Person 对象的数组进行排序。
我该怎么做?
您可以通过这种方式对用户定义的类进行降序排序,从而覆盖compare()方法,
Collections.sort(unsortedList,new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return b.getName().compareTo(a.getName());
}
});
或者通过使用排序降序作为用户Prince在他的评论中提到的。Collection.reverse()
你可以像这样做升序排序,
Collections.sort(unsortedList,new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
});
将上面的代码替换为 Lambda 表达式(Java 8 及更高版本),我们得到简洁:
Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));
从Java 8开始,List具有sort()方法,它将比较器作为参数(更简洁):
personList.sort((a,b)->b.getName().compareTo(a.getName()));
在这里,通过 lambda 表达式推断为 Person 类型。a
b
因为它的价值是我的标准答案。这里唯一的新内容是使用 Collections.reverseOrder()。另外,它将所有建议放在一个示例中:
/*
** Use the Collections API to sort a List for you.
**
** When your class has a "natural" sort order you can implement
** the Comparable interface.
**
** You can use an alternate sort order when you implement
** a Comparator for your class.
*/
import java.util.*;
public class Person implements Comparable<Person>
{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name + " : " + age;
}
/*
** Implement the natural order for this class
*/
public int compareTo(Person p)
{
return getName().compareTo(p.getName());
}
static class AgeComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
int age1 = p1.getAge();
int age2 = p2.getAge();
if (age1 == age2)
return 0;
else if (age1 > age2)
return 1;
else
return -1;
}
}
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
people.add( new Person("Homer", 38) );
people.add( new Person("Marge", 35) );
people.add( new Person("Bart", 15) );
people.add( new Person("Lisa", 13) );
// Sort by natural order
Collections.sort(people);
System.out.println("Sort by Natural order");
System.out.println("\t" + people);
// Sort by reverse natural order
Collections.sort(people, Collections.reverseOrder());
System.out.println("Sort by reverse natural order");
System.out.println("\t" + people);
// Use a Comparator to sort by age
Collections.sort(people, new Person.AgeComparator());
System.out.println("Sort using Age Comparator");
System.out.println("\t" + people);
// Use a Comparator to sort by descending age
Collections.sort(people,
Collections.reverseOrder(new Person.AgeComparator()));
System.out.println("Sort using Reverse Age Comparator");
System.out.println("\t" + people);
}
}