liveBook · Manning

Comparator.comparing

As explained in 100 Java Mistakes and How to Avoid Them

Comparator.comparing is a Java factory method that creates a comparator by extracting a comparison key from each object.

Comparator.comparing is a Java factory method that builds a comparator by extracting a comparison key from each object. Use it when an ordering should follow the values of one or more fields. section 7.13

The common mistake is returning 0 merely because the first key differs. That treats distinct objects as equivalent and can violate the comparator contract. Compare the first key, then continue with later keys only when it ties. section 7.13

Compare a sequence of keys

For MyObject records with x and y fields, use Comparator.comparing(MyObject::x).thenComparing(MyObject::y). This orders by x and uses y as the tie-breaker. If x is intentionally irrelevant, Comparator.comparing(MyObject::y) provides a complete alternative order. section 7.13

Avoid fragile comparison implementations by following these rules:

  • Represent the object as an ordered sequence of keys. section 7.13
  • Use thenComparing for tie-breakers and predefined primitive comparison methods where appropriate. section 7.15
  • Test comparator contract properties with randomized objects; sorting datasets larger than 31 elements can expose violations through TimSort. section 7.13
  • Handle nullable keys with nullsFirst or nullsLast rather than silently treating unrelated objects as equal. section 7.15

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains key extraction, tie-breaking, nullable keys, testing, and TimSort detection, but does not detail factory implementation internals.
Examples
Uses MyObject fields x and y, Person name and age, nullable User names, and randomized comparator property tests.
What you can do after
Build it from scratch as a key-based comparator and diagnose contract violations with randomized tests and larger sorting datasets.
How it connects
Connects Comparator.comparing to thenComparing, comparator contracts, equals, nullsFirst, nullsLast, ComparisonChain, and TimSort.

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.