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
