我有一个对象列表List<Student>
。
class Student {
private String name;
private Integer age;
private Integer rank
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return this.name;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getRank() {
return this.rank;
}
public void getRank(Integer rank) {
this.rank = rank;
}
}
我必须首先根据排名对排序进行排序,如果两个学生的排名相同,那么根据他们的年龄,以及他们的年龄是否相同,然后根据他们的名字。
任何人都可以帮忙吗? 感谢
答案 0 :(得分:1)
您可以使用java8 lambdas
List<Student> students = new Arraylist<>();
...
...
...
student.sort()
students.sort(Comparator.comparing(Student::getName).thenComparing(Student::getAge));
答案 1 :(得分:0)
在java8中,你有.thenComparing(...)方法
Comparator< Student> studentComparator = Comparator.comparing(student -> student.name);
comparator = comparator.thenComparing(Comparator.comparing(student -> student.age));
comparator = comparator.thenComparing(Comparator.comparing(student -> student.rank));
// Then pass this comparator in Collections#sort method
Collecions.sort(studentList, studentComparator); Your list will be sorted
答案 2 :(得分:0)
您可以将Guava用于Java 7以用于相同的用例。
请参阅:https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained#compare/compareTo.md