Category
collections
Slug
comparator-factories
Title
Comparator factories and fluent ordering
Difficulty
beginner
Since JDK
8
Summary
Build readable, composable ordering rules with Comparator factory methods.
Old code label
Anonymous comparator
Old code
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());
}
});
Modern code label
Java 8+
Modern code
people.sort(Comparator.comparing(Person::name)
.thenComparingInt(Person::age));
Explanation
Comparator factories express ordering declaratively and compose primary and secondary keys without handwritten branching.
Why the modern way wins
🧩 Composable — Ordering rules chain naturally.
👁 Easier to review — Sort keys and priority are explicit.
🐛 Safer comparisons — Specialized helpers avoid error-prone arithmetic comparators.
Category
collections
Slug
comparator-factories
Title
Comparator factories and fluent ordering
Difficulty
beginner
Since JDK
8
Summary
Build readable, composable ordering rules with Comparator factory methods.
Old code label
Anonymous comparator
Old code
Modern code label
Java 8+
Modern code
Explanation
Comparator factories express ordering declaratively and compose primary and secondary keys without handwritten branching.
Why the modern way wins
🧩 Composable — Ordering rules chain naturally.
👁 Easier to review — Sort keys and priority are explicit.
🐛 Safer comparisons — Specialized helpers avoid error-prone arithmetic comparators.