๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Java Programming Foundations Module 4 ยท Lesson 11 of 15

0% Exit to course

Module 4 ยท The standard library, in depth Lesson 11 of 15

Comparable, Comparator and sorting

Learning objective

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.

Java
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.

Create free account or sign in

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.

Next recommended course Python for Absolute Beginners