Sub topic 6
Writing comparators with lambdas and method references
Assume you know Java classes, interfaces, generics, lists, and basic lambda expressions. This chapter focuses on writing a Comparator, which is an object that compares two values and decides their order.
What a comparator does
A comparator has one main method:
int compare(T left, T right)The result has three meanings:
- A negative value means
leftcomes beforeright. - Zero means the comparator considers them equal for this ordering.
- A positive value means
leftcomes afterright.
The exact numbers do not matter. Only their signs matter.
A lambda is a short way to implement the method:
Comparator<String> byLength =
(left, right) -> Integer.compare(left.length(), right.length());This comparator orders strings from shortest to longest.
Writing a comparator with a lambda
Suppose a Person has a name and an age. You can create different orderings without changing the Person class.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorLambdaExample {
static class Person {
private final String name;
private final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
String getName() {
return name;
}
int getAge() {
return age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Ana", 31));
people.add(new Person("Bo", 25));
people.add(new Person("Cy", 31));
Comparator<Person> byAge =
(first, second) -> Integer.compare(first.getAge(), second.getAge());
people.sort(byAge);
System.out.println(people);
}
}The lambda parameters, first and second, represent the two people being compared. Integer.compare safely compares their ages.
You can also write the comparator directly where it is used:
people.sort((first, second) ->
Integer.compare(first.getAge(), second.getAge()));Give the comparator a variable when you will reuse it or when a descriptive name makes the code easier to understand.
Using method references
A method reference is a shorter form for a lambda that only calls an existing method. For example:
Comparator<Person> byName =
(first, second) -> Person.compareNames(first, second);If compareNames is a compatible static method, the same comparator can use a method reference:
Comparator<Person> byName = Person::compareNames;Here is the required method:
static int compareNames(Person first, Person second) {
return first.getName().compareTo(second.getName());
}The method reference means “call Person.compareNames with the two comparator arguments.” It does not call the method immediately.
A method reference can also refer to an instance method when the lambda forwards one object:
Comparator<String> alphabetic =
String::compareTo;This is equivalent to:
Comparator<String> alphabetic =
(first, second) -> first.compareTo(second);Common mistakes
Do not return an arbitrary Boolean. A comparator must return an integer:
// Incorrect: this returns only true or false
// (first, second) -> first.getAge() < second.getAge()Do not compare numbers by subtraction. Subtraction can overflow:
// Unsafe
(first, second) -> first.getAge() - second.getAge()
// Safe
(first, second) -> Integer.compare(first.getAge(), second.getAge())A comparator should also be consistent. If it says a comes before b, reversing the arguments should say b comes after a.
Exercise
Write a lambda comparator that orders strings by length, with shorter strings first.
Show answer
Comparator<String> byLength = (first, second) -> Integer.compare(first.length(), second.length());