Course contentsShow
← Java
Lesson 1342 of 2,87030. Comparable and ComparatorFree lesson

Chaining with thenComparing() for Secondary Sorts

Chain multiple sorting criteria using thenComparing() to break ties from the primary comparator.

Chaining with thenComparing() for Secondary Sorts

You'll learn how to combine multiple sorting criteria so ties in the primary sort are broken by secondary (and even tertiary) comparisons.

The Core Idea

Sometimes sorting by a single field isn't enough. Imagine sorting people by last name—what happens when two people share the same last name? You need a tiebreaker, like first name. The thenComparing() method lets you chain additional comparison logic that activates only when the primary comparator returns zero (meaning the elements are "equal" by the first criterion).

Think of it like sorting a deck of cards: first by suit, then by rank within each suit.

How It Works

After creating a primary Comparator with comparing(), you can call thenComparing() directly on it. The secondary comparator only evaluates when the primary comparison results in a tie:

Comparator<Person> byLastNameThenFirstName = 
    Comparator.comparing(Person::getLastName)
              .thenComparing(Person::getFirstName);

You can chain multiple levels:

Comparator<Employee> multiLevel = 
    Comparator.comparing(Employee::getDepartment)
              .thenComparing(Employee::getSalary)
              .thenComparing(Employee::getLastName);

This sorts by department first, then by salary within each department, then by last name if salaries match.

Primitive Specializations in Chains

Just like comparing(), thenComparing() has primitive variants to avoid boxing overhead:

Comparator<Product> byCategory = 
    Comparator.comparing(Product::getCategory)
              .thenComparingInt(Product::getPrice)
              .thenComparing(Product::getName);

Key Takeaway: Use thenComparing() to chain multiple sorting criteria, creating sophisticated multi-level sort orders where each level acts as a tiebreaker for the previous one—all in a clean, readable fluent API.