Possible Duplicate:
Sorting Java objects using multiple keys
我找不到任何使用这种方法的例子,所有例子都给第二个参数“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) 方法
最佳答案
在您现有的 Student 类(class)的基础上,这是我通常的做法,尤其是在我需要多个比较器的情况下。
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 大大简化。 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);
}
关于java - 集合 sort(List<T>,Comparator<? super T>) 方法示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14154127/