newbie newbie - 2 months ago 7
Java Question

How to sort an attribute of an object using Collections

Good day!

I have an object student with the following attributes:

class Student
String name
Date birthday


I used arrayList to store the Student Objects
My problem is, how can I sort the StudentList by birthday using the collecitons sort?.

List <Student> studentList = new ArrayList<Student>();


How can I code it?

Collections.sort(????);

Thank you

Answer

You can pass a Comparator to Collections.sort() to handle the sorting by birthday:

Collections.sort(studentList, new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        return s1.getBirthday().compareTo(s2.getBirthday());
    }
});

You'll need to add getBirthday() to your Student class if you don't have it already.

Comments