A custom comparator is applied in a stream pipeline by passing a Comparator implementation, often built with Comparator.comparing(), to the sorted() intermediate operation, letting you control ordering by any field or combination of fields.
employees.stream().sorted(Comparator.comparing(Employee::getDepartment).thenComparing(Employee::getName)) sorts employees first by department, then alphabetically by name within each department.
List<Employee> employees = getEmployees();
List<Employee> sorted = employees.stream()
.sorted(Comparator.comparing(Employee::getSalary).reversed())
.collect(Collectors.toList());A concise interview answer is
I build a Comparator with Comparator.comparing() and a key extractor, optionally chaining thenComparing() for tie-breaks or reversed() for descending order, then pass it straight into sorted() in the pipeline. It keeps sorting logic declarative and lets me sort by fields that aren't naturally Comparable.
Last updated: 16 July 2026
Previous question: What is the difference between Stream.iterate() and Stream.generate()?
Next question: Can you explain why Java 8 introduced the concept of Default Methods in interfaces, and what problem does it solve?