Collections Beginner

Comparator factories and fluent ordering

Build readable, composable ordering rules with Comparator factory methods.

✕ Anonymous comparator
people.sort(new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        int byName = a.name().compareTo(b.name());
        return byName != 0 ? byName : Integer.compare(a.age(), b.age());
    }
});
✓ Java 8+
people.sort(Comparator.comparing(Person::name)
        .thenComparingInt(Person::age));
See a problem with this code? Let us know.
🧩

Composable

Ordering rules chain naturally.

👁

Easier to review

Sort keys and priority are explicit.

🐛

Safer comparisons

Specialized helpers avoid error-prone arithmetic comparators.

Old Approach
Anonymous Comparator
Modern Approach
Comparator factories
Since JDK
8
Difficulty
Beginner
Comparator factories and fluent ordering
Available

Available since JDK 8 (March 2014)

Comparator factories express ordering declaratively and compose primary and secondary keys without handwritten branching.