liveBook · Manning

Comparator combinator

As explained in 100 Java Mistakes and How to Avoid Them

A comparator combinator is a method that constructs or composes a comparator from comparison criteria and ordering rules.

A comparator combinator constructs ordering by comparing keys in sequence: compare the first criterion, then proceed to the next only when equal. Java’s Comparator.comparing and thenComparing provide this pattern for custom comparators. section 7.13

Use combinators to avoid common comparison-method mistakes:

  • Represent the object as ordered keys, such as name followed by age, rather than scattering special cases through compareTo. section 7.13
  • For priority rules, compare the derived key first; a secure-connection flag can precede the URL. section 7.13
  • Handle nullable keys explicitly with nullsLast or nullsFirst before comparing non-null values. section 7.13
  • Do not return zero merely because the first key differs; doing so can make distinct objects compare equal. section 7.13

Name, then age

Comparator<Person> order = Comparator.comparing((Person p) -> p.name).thenComparing(p -> p.age); A Comparable implementation can delegate compareTo to this comparator. section 7.13

Comparator<Person> PERSON_COMPARATOR =
    Comparator.comparing((Person p) -> p.name)
              .thenComparing(p -> p.age);

Browse a focused Java comparator chain that orders Person objects by name and then age. section 7.13

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains sequential keys, priority flags, nullable keys, and contract failures with Java and Guava alternatives.
Examples
Uses Person name-and-age ordering, secure connections before URLs, nullable User names, and a faulty two-key comparator.
What you can do after
Build it from scratch with Comparator.comparing, thenComparing, Boolean ordering, and explicit null-ordering combinators.
How it connects
Connects Comparator combinators with Comparable, ComparisonChain, key ordering, null handling, and comparison-method contracts.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.