在你现有的学生班级的基础上,这通常是我的工作方式,尤其是当我需要多个比较器时。
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实现,其中考虑了这些更改。
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);}


