我找不到使用此方法的任何示例,所有示例都给出第二个参数“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);
}
}
这个课程,如果我想根据他们的名字排序学生名单&amp;我怎样才能使用方法集合排序(List,Comparator)
答案 0 :(得分:98)
以现有的 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发布以来,使用lambdas可以大大简化内部类Comparators
。 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);
}
答案 1 :(得分:55)
这可能是最简单的方法 -
Collections.sort(listOfStudent,new Comparator<Student>(){
public int compare(Student s1,Student s2){
// Write your logic here.
}});
使用Java 8(lambda表达式) -
listOfStudent.sort((s1, s2) -> s1.age - s2.age);
答案 2 :(得分:9)
你可能想要这样的东西:
Collections.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
return s1.getName().compareTo(s2.getName());
} else {
return s1.getAge().compareTo(s2.getAge());
}
}
);
这首先按名字对学生进行排序。如果缺少姓名,或者两名学生姓名相同,则按年龄排序。
答案 3 :(得分:1)
要使用集合排序(List,Comparator),您需要创建一个实现Comparator接口的类,并通过Comparator Interface
创建其中compare()的代码您可以这样做:
class StudentComparator implements Comparator
{
public int compare (Student s1 Student s2)
{
// code to compare 2 students
}
}
要对此进行排序:
Collections.sort(List,new StudentComparator())