Module 4 ยท The standard library, in depth Lesson 11 of 15
Comparable, Comparator and sorting
Comparable makes a class know its own natural order; Comparator sorts by any rule you like, including several at once. Sorting objects by two fields is a routine task and a routine question.
The concept
Use Comparable for the one obvious order of the type and Comparator for every other order, so callers choose rather than the class deciding.
Comparator.comparing with method references removes the boilerplate compareTo body that used to make sorting look harder than it is.
class Student implements Comparable<Student> {
public int compareTo(Student o) { return Integer.compare(id, o.id); }
}
students.sort(Comparator.comparing(Student::getMarks)
.reversed()
.thenComparing(Student::getName));Worked example
students.sort(Comparator.comparing(Student::getMarks).reversed().thenComparing(Student::getName)) sorts by marks descending, then by name.
Your practice task
Sort five students first by marks descending and then by name, using a Comparator chain.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
Use Comparable for the one obvious order of the type and Comparator for every other order, so callers choose rather than the class deciding.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.