Sub topic 10
Sorting with Comparable and Comparator
Sorting means putting items in order, such as from smallest to largest or from A to Z. Java can sort strings and numbers on its own. It can't sort your own classes until you tell it how to compare two objects. Java gives you two ways to do that: Comparable and Comparator.
How Java compares two objects
Every sort in Java asks the same question over and over: "Does a come before b?" The answer is a single int:
- A negative number means
acomes first. - Zero means
aandbare equal for sorting purposes. - A positive number means
bcomes first.
Comparable: the natural order
Comparable is an interface. A class implements it to define its natural order, which is the one default way its objects are sorted. You write one method, compareTo. String and Integer already implement Comparable, and that is why they sort alphabetically and numerically.
Comparator: any order you want
A Comparator is a separate object that compares two values. It lets you sort the same class in many different ways without changing the class itself. You build one with helper methods:
| Method | What it does |
|---|---|
| `Comparator.comparing(f)` | Compares by the value `f` returns |
| `Comparator.comparingInt(f)` | Same idea, for an `int` value |
| `.reversed()` | Flips the order |
| `.thenComparing(f)` | Breaks ties with a second rule |
| `Comparator.naturalOrder()` | Uses `compareTo` |
Worked example
This Student class sorts by age by default. The main method then sorts the same list in other orders with comparators.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Student implements Comparable<Student> {
private final String name;
private final int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
@Override
public int compareTo(Student other) {
return Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return name + "(" + age + ")";
}
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Cara", 25),
new Student("Ana", 30),
new Student("Ben", 25)));
Collections.sort(list); // natural order: by age
System.out.println(list); // [Cara(25), Ben(25), Ana(30)]
list.sort(Comparator.comparing(Student::getName));
System.out.println(list); // [Ana(30), Ben(25), Cara(25)]
list.sort(Comparator.comparingInt(Student::getAge).reversed());
System.out.println(list); // [Ana(30), Ben(25), Cara(25)]
list.sort(Comparator.comparingInt(Student::getAge)
.thenComparing(Student::getName));
System.out.println(list); // [Ben(25), Cara(25), Ana(30)]
}
}In the first sort, Cara and Ben are both 25, so they stay in the order they started in. Java's list sort is stable: a stable sort keeps equal items in their earlier order. The last sort adds thenComparing, which uses the name to break the tie, so Ben comes before Cara.
Which one to use
Use Comparable when your class has one obvious order, such as dates by time. Use a Comparator when you need a different order, or several orders, or when you can't edit the class. The next chapter shows how sorted collections such as TreeSet use these same rules.
Exercise
Write a Comparator that sorts a List<String> by length from longest to shortest, and alphabetically when two strings have the same length. What order does it give for ["fig", "kiwi", "apple", "pear"]?
Show answer
Comparator.comparing(String::length).reversed().thenComparing(Comparator.naturalOrder()). The result is [apple, kiwi, pear, fig].
Exercise
A compareTo method returns 0 for two different objects. What does the sort do with them?
Show answer
The sort treats them as equal in order. Because the sort is stable, they keep the relative order they had before sorting.