Learnitweb

Sort a List of Objects by Multiple Fields

Approach 1 — thenComparing

employees.stream()
    .sorted(Comparator.comparing(Employee::getDept)
    .thenComparing(Employee::getName))
    .toList();

Approach 2 — Combined Lambda Comparator

employees.stream()
    .sorted((a,b) -> {
        int r = a.getDept().compareTo(b.getDept());
        return r != 0 ? r : a.getName().compareTo(b.getName());
    })
    .toList();

Explanation:

  • thenComparing chains multiple comparisons for clarity.
  • Null handling is possible using Comparator.nullsFirst or nullsLast.