在您现有的Student课程的基础上,这就是我通常的做法,尤其是在我需要多个比较器的情况下。
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
可以使用 lambdas 大大简化。Comparator
Java 8 还为object引入了一种新方法,thenComparing
在嵌套它们时无需手动检查每个比较器。Student.Comparators
下面是考虑了这些更改的类的 Java 8 实现。
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);
}