美好的一天!
我有一个具有以下属性的对象学生:
class Student
String name
Date birthday
Run Code Online (Sandbox Code Playgroud)
我使用arrayList来存储学生对象我的问题是,如何使用collecitons排序按生日对StudentList进行排序?
List <Student> studentList = new ArrayList<Student>();
Run Code Online (Sandbox Code Playgroud)
我该如何编码呢?
Collections.sort(????);
谢谢
Whi*_*g34 20
你可以传递一个Comparator
来Collections.sort()
处理生日排序:
Collections.sort(studentList, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getBirthday().compareTo(s2.getBirthday());
}
});
Run Code Online (Sandbox Code Playgroud)
如果你还没有getBirthday()
,你需要加入你的Student
班级.
在Java 8中,您可以使用Lambda表达式和Comparator以单线对列表进行排序。比较:
Collections.sort(studentList, Comparator.comparing(s -> s.getBirthday()));
Run Code Online (Sandbox Code Playgroud)
另外,您可以使用方法参考:
Collections.sort(studentList, Comparator.comparing(Student::getBirthday));
Run Code Online (Sandbox Code Playgroud)