Course contentsShow
← Java
Lesson 1451 of 2,87032. Streams API: Intermediate OperationsFree lesson

sorted with Custom Comparators

Pass a Comparator to sorted() to define custom ordering logic for stream elements.

sorted with Custom Comparators

What you'll learn: How to pass a Comparator to the sorted() stream operation to define custom ordering logic beyond natural ordering.


The Core Idea

While sorted() without arguments uses natural ordering (what objects consider their "default" sort order), the real power comes from sorted(Comparator<T>). By passing a Comparator, you tell the stream exactly how to order elements—whether by specific fields, in reverse, by complex business rules, or any custom logic you define.

Think of it like giving explicit instructions to a librarian: instead of alphabetizing books by title automatically, you might say "sort by author's last name" or "sort by page count, shortest first."

Basic Syntax

stream.sorted(Comparator.comparing(Person::getAge))

This passes a Comparator that extracts the age property and sorts by it.

Common Patterns

Sort by a specific field:

people.stream()
      .sorted(Comparator.comparing(Person::getName))
      .forEach(System.out::println);

Reverse order:

numbers.stream()
       .sorted(Comparator.reverseOrder())
       .collect(Collectors.toList());

Chain comparators for multi-level sorting:

employees.stream()
         .sorted(Comparator.comparing(Employee::getDepartment)
                           .thenComparing(Employee::getSalary))
         .forEach(System.out::println);

Why Custom Comparators Matter

Natural ordering doesn't exist for every type, and even when it does, it might not match your needs. Custom comparators let you control sorting without modifying your classes or relying on their Comparable implementation.

Key Takeaway: Pass a Comparator to sorted() to define any custom ordering logic—by field extraction, reverse order, or complex multi-level criteria—giving you complete control over how stream elements are arranged.