Sub topic 5
Comparator: Ordering from Outside the Class
Assume you know Java classes, interfaces, generics, lists, equals and hashCode, lambda expressions, and method references. This chapter uses Java 8 or later.
A Comparator<T> is an object that defines how to compare two values of type T. Unlike Comparable, which places an ordering inside a class, a comparator keeps the ordering outside the class.
This separation is useful when:
- A class needs several valid orderings.
- You cannot modify the class being sorted.
- The ordering depends on the current task.
- The natural ordering of the class is not appropriate for one operation.
The Comparator interface
The central method is:
int compare(T left, T right)The result has meaning only by its sign:
| Result | Meaning |
|---|---|
| Negative | `left` comes before `right` |
| Zero | The values are equal for this ordering |
| Positive | `left` comes after `right` |
The exact value does not matter. Returning -1, 0, or 1 is common, but any negative or positive value is valid.
Here is a complete example that sorts products by price without adding sorting logic to Product:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
static class Product {
private final String name;
private final int priceInCents;
Product(String name, int priceInCents) {
this.name = name;
this.priceInCents = priceInCents;
}
String getName() {
return name;
}
int getPriceInCents() {
return priceInCents;
}
@Override
public String toString() {
return name + " ($" + priceInCents + " cents)";
}
}
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
products.add(new Product("Keyboard", 4500));
products.add(new Product("Mouse", 2500));
products.add(new Product("Monitor", 18000));
Comparator<Product> byPrice =
(first, second) ->
Integer.compare(first.getPriceInCents(),
second.getPriceInCents());
products.sort(byPrice);
System.out.println(products);
}
}The byPrice object is a comparison strategy. The Product class describes products, while the comparator describes one way to order them.
Lambdas and method references
A lambda is often the shortest way to create a comparator:
Comparator<String> byLength =
(first, second) -> Integer.compare(first.length(), second.length());When a comparison follows a standard rule, a method reference can be clearer:
Comparator<String> alphabetical = String::compareTo;You can pass a comparator directly to a sorting method:
products.sort((first, second) ->
Integer.compare(first.getName().length(),
second.getName().length()));This is convenient for a one-time ordering. Give the comparator a name when you reuse it or when the comparison needs explanation.
Where comparators are used
Many Java APIs accept a comparator:
List.sort(comparator)sorts a list in place.Collections.sort(list, comparator)sorts a list using the supplied ordering.Arrays.sort(array, comparator)sorts object arrays.Stream.sorted(comparator)creates a stream with sorted elements.TreeSet,TreeMap, andPriorityQueuecan use a comparator to define their ordering.
The same comparator can therefore be shared across several operations.
Comparing values safely
Do not compare integers by subtraction:
Comparator<Integer> unsafe = (first, second) -> first - second;Subtraction can overflow. For example, subtracting a negative value from Integer.MAX_VALUE can produce a negative result even though the first value is larger.
Use Integer.compare instead:
Comparator<Integer> safe = Integer::compare;For object fields, compare the fields with their own safe comparison methods. This keeps the comparator correct even for extreme values.
Exercise
You have a List<String> names. Write a comparator that sorts names by descending length, and keeps alphabetical order when two names have the same length.
Show answer
Use a length comparison first, reverse it for descending order, then compare the names:
Comparator<String> byLengthDescendingThenName = Comparator.comparingInt(String::length) .reversed() .thenComparing(String::compareTo);