可能重复:
使用多个键对Java对象进行排序
我找不到使用此方法的任何示例,所有示例都给出第二个参数"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);
}
Run Code Online (Sandbox Code Playgroud)
}
对于这个类,如果我想根据他们的姓名和年龄对学生列表进行排序我如何使用方法集合排序(List,Comparator)
ato*_*man 103
在现有的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;
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
List<Student> studentList = new LinkedList<>();
Collections.sort(studentList, Student.Comparators.AGE);
Run Code Online (Sandbox Code Playgroud)
编辑
自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);
}
Run Code Online (Sandbox Code Playgroud)
Sub*_*der 58
这可能是最简单的方法 -
Collections.sort(listOfStudent,new Comparator<Student>(){
public int compare(Student s1,Student s2){
// Write your logic here.
}});
Run Code Online (Sandbox Code Playgroud)
使用Java 8(lambda表达式) -
listOfStudent.sort((s1, s2) -> s1.age - s2.age);
Run Code Online (Sandbox Code Playgroud)
Ale*_*øld 10
你可能想要这样的东西:
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());
}
}
);
Run Code Online (Sandbox Code Playgroud)
这首先按名称对学生进行排序.如果缺少姓名,或者两名学生姓名相同,则按年龄排序.
归档时间: |
|
查看次数: |
245191 次 |
最近记录: |