0Pricing
Java Academy · Lesson

Multi-Key Sorting with thenComparing

Chain comparators with thenComparing to sort by multiple fields in order of priority.

Multi-Key Sorting

thenComparing() chains comparators to sort by multiple fields. Primary sort first; if equal, secondary sort; and so on.

Basic thenComparing

Use thenComparing() to break ties after the primary comparator.

import java.util.*;

record Student(String name, int grade, double gpa) {}

List<Student> students = List.of(
    new Student("Alice",   10, 3.9),
    new Student("Bob",     11, 3.7),
    new Student("Charlie", 10, 3.8),
    new Student("Diana",   11, 3.7)
);

Comparator<Student> sort = Comparator.comparingInt(Student::grade)
    .thenComparingDouble(Student::gpa).reversed()
    .thenComparing(Student::name);

students.stream().sorted(sort).forEach(System.out::println);

All lessons in this course

  1. The Comparable Interface
  2. Comparator and Lambda Sorting
  3. Multi-Key Sorting with thenComparing
  4. Sorting Arrays and Collections in Practice
← Back to Java Academy