Sub topic 10
Sorting with Comparable and Comparator
Lists keep elements in the order you added them. Often you want a different order: names A to Z, scores from high to low, or books by author. Java gives you two tools for this. Comparable is an interface a class implements to define its own "natural" order. Comparator is a separate object that describes an order from outside the class. This chapter shows both, how to sort a list with them, and the mistakes beginners often make.
How Java compares two things
Every sort needs one basic question answered again and again: "Does a come before b?" Java answers it with a number. A compare method takes two elements and returns an int:
| Return value | Meaning |
|---|---|
| Negative (for example -1) | `a` comes before `b` |
| Zero | `a` and `b` are equal for sorting purposes |
| Positive (for example 1) | `a` comes after `b` |
Only the sign matters. The exact value does not. A return of -5 means the same thing as -1.
Natural order with Comparable
Many built-in classes already know how to compare themselves. Integer, Double, String, and LocalDate all implement Comparable. The order they define is called their natural order. Numbers go from small to large. Strings go in dictionary-like order, based on character codes.
Collections.sort(list) sorts a list in natural order. list.sort(Comparator.naturalOrder()) does the same thing.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NaturalOrderDemo {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>(List.of(42, 7, 19, 7));
Collections.sort(scores);
System.out.println(scores); // [7, 7, 19, 42]
List<String> words = new ArrayList<>(List.of("cherry", "apple", "Banana"));
Collections.sort(words);
System.out.println(words); // [Banana, apple, cherry]
words.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(words); // [apple, Banana, cherry]
}
}Look at the second result. "Banana" comes before "apple" because uppercase letters have lower character codes than lowercase ones. If you want "a" and "A" treated alike, use String.CASE_INSENSITIVE_ORDER, which is a ready-made Comparator.
Giving your own class a natural order
Your own classes have no natural order until you give them one. To add one, implement Comparable<T> and write a compareTo method. The method compares this object with other.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Student implements Comparable<Student> {
private final String name;
private final int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() { return name; }
public int getId() { return id; }
@Override
public int compareTo(Student other) {
return Integer.compare(this.id, other.id);
}
@Override
public String toString() {
return name + "#" + id;
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Cara", 30));
students.add(new Student("Ana", 12));
students.add(new Student("Ben", 21));
Collections.sort(students);
System.out.println(students); // [Ana#12, Ben#21, Cara#30]
}
}Integer.compare(x, y) returns a negative number, zero, or a positive number, which is exactly what compareTo must return. For strings, call this.name.compareTo(other.name).
If you call Collections.sort on a list of objects that do not implement Comparable, the code will not compile. With some other methods, such as adding to a TreeSet, the code compiles and then fails at run time with ClassCastException.
The subtraction trap
You may see compareTo written as return this.id - other.id;. It looks shorter, but it can give the wrong answer. When the numbers are very large or very negative, the subtraction can overflow. Overflow means the result is too big for an int, so it wraps around and the sign flips.
public class OverflowDemo {
public static void main(String[] args) {
int a = Integer.MIN_VALUE;
int b = 1;
System.out.println(a - b); // 2147483647 (positive: wrong!)
System.out.println(Integer.compare(a, b)); // -1 (correct)
}
}a is clearly smaller than b, but a - b is positive. A sort that uses this result will put the elements in the wrong order. Always use Integer.compare, Long.compare, or Double.compare.
Other orders with Comparator
A class can have only one natural order. You often need more than one. You might sort students by id in one place and by name in another. A Comparator solves this. It is an object with a compare(a, b) method, and you pass it to sort.
You rarely write a Comparator class by hand. The Comparator interface has helper methods that build one for you:
| Method | What it builds |
|---|---|
| `Comparator.comparing(Book::getTitle)` | Order by a key taken from each element |
| `Comparator.comparingInt(Book::getYear)` | Same, for an `int` key, without boxing |
| `.reversed()` | The opposite order |
| `.thenComparing(Book::getTitle)` | A tie-breaker used when the first key is equal |
| `Comparator.naturalOrder()` / `reverseOrder()` | Natural order, or its reverse |
| `Comparator.nullsFirst(...)` / `nullsLast(...)` | Puts `null` elements first or last instead of crashing |
Book::getTitle is a method reference. It is short for the lambda b -> b.getTitle(), which means "given a book, get its title."
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Book {
private final String title;
private final String author;
private final int year;
Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.year = year;
}
String getTitle() { return title; }
String getAuthor() { return author; }
int getYear() { return year; }
@Override
public String toString() {
return title + " (" + year + ")";
}
}
public class ComparatorDemo {
public static void main(String[] args) {
List<Book> books = new ArrayList<>();
books.add(new Book("Dune", "Herbert", 1965));
books.add(new Book("Emma", "Austen", 1815));
books.add(new Book("Persuasion", "Austen", 1817));
books.add(new Book("Neuromancer", "Gibson", 1984));
books.sort(Comparator.comparing(Book::getTitle));
System.out.println(books);
// [Dune (1965), Emma (1815), Neuromancer (1984), Persuasion (1817)]
books.sort(Comparator.comparingInt(Book::getYear).reversed());
System.out.println(books);
// [Neuromancer (1984), Dune (1965), Persuasion (1817), Emma (1815)]
books.sort(Comparator.comparing(Book::getAuthor)
.thenComparing(Book::getTitle));
System.out.println(books);
// [Emma (1815), Persuasion (1817), Neuromancer (1984), Dune (1965)]
books.sort((a, b) -> Integer.compare(a.getTitle().length(),
b.getTitle().length()));
System.out.println(books);
// [Emma (1815), Dune (1965), Persuasion (1817), Neuromancer (1984)]
}
}The third sort uses a tie-breaker. Two books share the author "Austen", so thenComparing orders those two by title. The last sort shows that you can also write the comparison yourself as a lambda.
Sorting is stable
List.sort and Collections.sort are stable. A stable sort never reorders elements that compare as equal. Look at the last sort above. "Emma" and "Dune" both have four letters, so they are equal by length. "Emma" was before "Dune" in the list going in, so it stays before "Dune" in the result.
You can use stability on purpose. Sorting by the less important key first and then by the more important key gives the same result as thenComparing. thenComparing is still clearer, so prefer it.
Where Comparators show up besides List.sort
The same Comparator objects work in many places in the framework:
Collections.max(list, comparator)andCollections.min(list, comparator)find the largest or smallest element.TreeSetandTreeMaptake a Comparator in their constructor to keep elements sorted at all times. Later chapters cover these.- Streams use them in
sorted(comparator)andmax(comparator).
Common mistakes
- Sorting an unmodifiable list.
List.of(...).sort(...)throwsUnsupportedOperationException. Copy the list into anArrayListfirst. - Subtracting in compareTo. Use
Integer.compareto avoid overflow. - Nulls in the list. Natural order throws
NullPointerExceptionon anullelement. Wrap your Comparator inComparator.nullsLast(...)if nulls can appear. - compareTo that disagrees with equals. If
compareToreturns 0 for two objects thatequalssays are different, aTreeSetwill keep only one of them. Try to make "compares as zero" and "equal" mean the same thing. - Forgetting that sort changes the list.
list.sort(...)changes the list in place and returns nothing. Make a copy first if you still need the original order.
Exercise
You have a List<Student> (from the Student class above). Write one line that sorts it by name A to Z, and when two students share a name, by id from highest to lowest.
Show answer
students.sort(Comparator.comparing(Student::getName).thenComparing(Comparator.comparingInt(Student::getId).reversed())); The reversed comparator is passed into thenComparing, so only the tie-breaker is reversed. Calling .reversed() at the end of the whole chain would reverse the name order too.
Exercise
A classmate writes public int compareTo(Account other) { return this.balance - other.balance; }, where balance is an int. Why is this risky, and what should it be?
Show answer
The subtraction can overflow for very large or very negative balances, which flips the sign and gives the wrong order. Write return Integer.compare(this.balance, other.balance); instead.
Exercise
The list ["kiwi", "fig", "plum", "pear"] is sorted with Comparator.comparing(String::length). What is the result, and why are the four-letter words in that order?
Show answer
[fig, kiwi, plum, pear]. "fig" has 3 letters, so it comes first. The other three words all have 4 letters and compare as equal. List.sort is stable, so they keep their original relative order: kiwi, plum, pear.