Sub topic 6
Writing comparators with lambdas and method references
This chapter assumes you know Java generics, the basic lambda syntax, and what Comparable and the compare contract require. The earlier chapters cover those. Here you write Comparator instances in their shortest correct forms and learn where each form is safe to use.
Why Comparator fits a lambda
A lambda expression can implement any interface that has exactly one abstract method, called a functional interface. Comparator<T> qualifies. It declares equals(Object), but that method matches one in Object, so it does not count. The only abstract method is int compare(T a, T b).
The compiler therefore turns a lambda into a Comparator whenever the target type is a Comparator. The target type can be a variable, a method parameter such as the one in List.sort, or a return type. The lambda body must follow the same contract as compare: return a negative number, zero or a positive number, and stay consistent.
From anonymous class to lambda
The same ordering can be written in several ways. The program below uses a small record as the element type so that it runs by itself.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class LambdaComparators {
record Person(String name, int age) {}
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("Ana", 31), new Person("Bo", 25), new Person("Cy", 31)));
Comparator<Person> anonymous = new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return Integer.compare(a.age(), b.age());
}
};
Comparator<Person> typed = (Person a, Person b) -> Integer.compare(a.age(), b.age());
Comparator<Person> inferred = (a, b) -> Integer.compare(a.age(), b.age());
Comparator<Person> ageThenName = (a, b) -> {
int byAge = Integer.compare(a.age(), b.age());
if (byAge != 0) {
return byAge;
}
return a.name().compareTo(b.name());
};
people.sort(anonymous);
System.out.println(people.stream().map(Person::name).toList()); // [Bo, Ana, Cy]
people.sort(inferred.reversed());
System.out.println(people.stream().map(Person::name).toList()); // [Ana, Cy, Bo]
people.sort(ageThenName);
System.out.println(people.stream().map(Person::name).toList()); // [Bo, Ana, Cy]
System.out.println(typed.compare(people.get(0), people.get(1)) < 0); // true
}
}The four comparators sort by age. They differ only in syntax:
- The anonymous class is the verbose, pre-Java 8 form.
- The
typedlambda declares its parameter types. This is rarely needed, but it helps readability when inference is unclear. - The
inferredlambda lets the compiler inferPersonfrom the target typeComparator<Person>. - The
ageThenNamelambda has a block body. Use a block when the logic needs local variables or several steps. A block body needs an explicitreturn.
The last step in the diagram uses a factory method, which the next chapter covers in full. For simple key-based orderings it is usually clearer than a hand-written compare lambda. Write the lambda by hand when the logic does not reduce to "compare these extracted keys".
Method references as comparators
A method reference is a shorthand for a lambda that only calls one existing method. For a Comparator<T>, the compiler needs a method that can accept two T values and return an int. Four kinds of reference are common.
| Kind | Example | Equivalent lambda |
|---|---|---|
| Static method | `Integer::compare` | `(a, b) -> Integer.compare(a, b)` |
| Unbound instance method | `String::compareToIgnoreCase` | `(a, b) -> a.compareToIgnoreCase(b)` |
| Bound instance method | `rank::get` as a key extractor | `s -> rank.get(s)` |
| Static method of your own | `LambdaComparators::byLengthThenAlpha` | `(a, b) -> byLengthThenAlpha(a, b)` |
An unbound reference names the class, so the first parameter becomes the receiver and the second becomes the argument. This is why String::compareTo works as a Comparator<String>. A bound reference names a specific object, which is captured when the reference is created.
The next program shows each kind in use.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class MethodRefComparators {
static int byLengthThenAlpha(String a, String b) {
int byLength = Integer.compare(a.length(), b.length());
return byLength != 0 ? byLength : a.compareTo(b);
}
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(5, -3, 12, 0));
nums.sort(Integer::compare);
System.out.println(nums); // [-3, 0, 5, 12]
List<String> words = new ArrayList<>(List.of("pear", "apple", "Fig", "Banana"));
words.sort(String::compareTo);
System.out.println(words); // [Banana, Fig, apple, pear]
words.sort(String::compareToIgnoreCase);
System.out.println(words); // [apple, Banana, Fig, pear]
words.sort(MethodRefComparators::byLengthThenAlpha);
System.out.println(words); // [Fig, pear, apple, Banana]
Map<String, Integer> rank = Map.of("low", 1, "medium", 2, "high", 3);
Comparator<String> byRank = Comparator.comparing(rank::get);
List<String> levels = new ArrayList<>(List.of("high", "low", "medium"));
levels.sort(byRank);
System.out.println(levels); // [low, medium, high]
}
}String::compareTo puts "Banana" and "Fig" before "apple" because it compares UTF-16 code units, and uppercase letters have lower values than lowercase ones. Use String::compareToIgnoreCase or String.CASE_INSENSITIVE_ORDER for case-insensitive ordering. For text shown to users, a java.text.Collator respects locale rules that neither of those handles.
Giving a multi-step comparison a name, as byLengthThenAlpha does, has three benefits. You can unit test it directly, a stack trace shows a readable name, and several call sites can share it without copying the lambda.
Capturing variables
A lambda can read local variables from the enclosing method if they are final or effectively final, meaning they are never reassigned. That lets you build a comparator that depends on a runtime value.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ClosestToPivot {
record Person(String name, int age) {}
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("Ana", 31), new Person("Bo", 25), new Person("Cy", 31)));
int pivot = 30;
people.sort(Comparator.comparingInt(p -> Math.abs(p.age() - pivot)));
System.out.println(people.stream().map(Person::name).toList()); // [Ana, Cy, Bo]
}
}Ana and Cy are both one year from the pivot. List.sort is stable, so they keep their original relative order. Bo is five years away and comes last.
A comparator that captures a value is fine for a single sort. It needs more care when you store it in a long-lived structure such as a TreeSet. If the captured value is a mutable object that changes later, the ordering of elements already in the structure silently changes, and the structure can no longer find them.
Rules for comparator lambdas
The lambda syntax does not enforce the compare contract. These practices keep a comparator correct:
- Return an
intcomputed by a real comparison, such asInteger.compare,Double.compare,String.compareToorBoolean.compare. A lambda that returns abooleandoes not compile. - Return zero when two elements are equal under your ordering. Never skip the zero case.
- Keep the lambda free of side effects. A sort may call it many times, in an order you cannot predict.
- Use the same fields for every comparison, so the ordering is consistent from call to call.
- Do not compare with subtraction.
(a, b) -> a - boverflows for values far apart, as the pitfalls chapter shows. UseInteger.compare(a, b).
The most common lambda mistake is a ternary that never returns zero.
Comparator<Person> bad = (a, b) -> a.age() > b.age() ? 1 : -1;For two people of equal age, bad.compare(x, y) and bad.compare(y, x) both return -1. That violates the requirement that compare(x, y) and compare(y, x) have opposite signs. Small lists may sort without any error. Larger inputs can make List.sort or Arrays.sort throw IllegalArgumentException with the message "Comparison method violates its general contract!". Because the failure depends on data size, it tends to appear in production rather than in tests. The fix is Integer.compare(a.age(), b.age()).
Reuse and readability
Comparators have no state of their own unless they capture some, so one instance is safe to share across threads and reuse. A common pattern is to put frequently used orderings in static final fields:
static final Comparator<String> BY_LENGTH = Comparator.comparingInt(String::length);This avoids creating the same lambda at many call sites and gives the ordering a name that documents its purpose. For nonstatic lambdas that capture nothing, the JVM typically reuses a single instance anyway, but a named constant is clearer for readers.
Keep each lambda short. Once it passes a few lines, move it into a named method and refer to it with a method reference, as byLengthThenAlpha does above.
Summary of choices
| Situation | Preferred form |
|---|---|
| Compare one primitive or `Comparable` key | `Comparator.comparingInt(Person::age)` or `Comparator.comparing(...)` |
| Compare two values with an existing method | A method reference such as `String::compareToIgnoreCase` |
| Several steps or local variables | A lambda with a block body, or a named static method |
| Ordering reused in many places | A `static final` constant or a named method |
Exercise
When String::compareToIgnoreCase is used as a Comparator<String>, which kind of method reference is it, and what lambda is it equivalent to?
Show answer
It is an unbound instance method reference. The first comparator argument becomes the receiver and the second becomes the method argument, so it is equivalent to (a, b) -> a.compareToIgnoreCase(b).
Exercise
The lambda (a, b) -> a.age() > b.age() ? 1 : -1 is used as a Comparator<Person>. Explain what is wrong with it and write a corrected version.
Show answer
For equal ages it returns -1 in both directions, which violates the rule that compare(x, y) and compare(y, x) have opposite signs. On large inputs the sort can throw IllegalArgumentException with "Comparison method violates its general contract!". The corrected version is (a, b) -> Integer.compare(a.age(), b.age()), or Comparator.comparingInt(Person::age).