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
Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.
So, in the end, Collections#sort uses Arrays#sort (of object elements) behind the scenes. This implementation uses merge sort or tim sort.
Summary. Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.
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.
In Java 8 you can sort the list with a one-liner using Lambda expressions and Comparator.comparing:
Collections.sort(studentList, Comparator.comparing(s -> s.getBirthday()));
Alternatively you can use the method reference:
Collections.sort(studentList, Comparator.comparing(Student::getBirthday));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With