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
- The Comparable Interface
- Comparator and Lambda Sorting
- Multi-Key Sorting with thenComparing
- Sorting Arrays and Collections in Practice