如何使用集合对对象的属性进行排序

new*_*bie 10 java

美好的一天!

我有一个具有以下属性的对象学生:

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

你可以传递一个ComparatorCollections.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班级.


Ste*_*lis 5

在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)