Sitelet https://github.com/javaevolved/javaevolved.github.io/issues/174
Skip to content

[Pattern] Comparator factories and fluent ordering #174

Description

@brunoborges

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    slugNew or updated pattern snippet (category/slug.json)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions