我找不到使用此方法的任何示例,所有示例都给出了第二个参数“ null”。我听说此方法用于根据多个标准对类进行排序,但找不到示例。
public class Student implements Comparable<Student> { String name; int age; public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return name + ":" + age; } @Override public int compareTo(Student o) { Integer myAge = age; Integer oAge = o.age; return myAge.compareTo(oAge); } }
对于本课程,如果我想根据学生的姓名和年龄对学生列表进行排序,如何使用方法Collections sort(List,Comparator)
在你现有的学生班级的基础上,这通常是我的工作方式,尤其是当我需要多个比较器时。
public class Student implements Comparable<Student> { String name; int age; public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return name + ":" + age; } @Override public int compareTo(Student o) { return Comparators.NAME.compare(this, o); } public static class Comparators { public static Comparator<Student> NAME = new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.name.compareTo(o2.name); } }; public static Comparator<Student> AGE = new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.age - o2.age; } }; public static Comparator<Student> NAMEANDAGE = new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { int i = o1.name.compareTo(o2.name); if (i == 0) { i = o1.age - o2.age; } return i; } }; } }
用法:
List<Student> studentList = new LinkedList<>(); Collections.sort(studentList, Student.Comparators.AGE);
编辑
自Java 8发行以来,Comparators使用lambda可以大大简化内部类。Java 8还为该Comparator对象引入了一种新方法,该方法thenComparing无需在嵌套每个比较器时进行手动检查。下面是Student.Comparators该类的Java 8实现,其中考虑了这些更改。
Comparators
lambda
Comparator
thenComparing
Student.Comparators
public static class Comparators { public static final Comparator<Student> NAME = (Student o1, Student o2) -> o1.name.compareTo(o2.name); public static final Comparator<Student> AGE = (Student o1, Student o2) -> Integer.compare(o1.age, o2.age); public static final Comparator<Student> NAMEANDAGE = (Student o1, Student o2) -> NAME.thenComparing(AGE).compare(o1, o2); }