Course contentsShow
← Java
Lesson 1360 of 2,87030. Comparable and ComparatorFree lesson

Sorting Streams with sorted(Comparator)

Using the sorted() intermediate operation with Comparators in stream pipelines.

Sorting Streams with sorted(Comparator)

What you'll learn: How to sort elements within a Java stream pipeline using the sorted() intermediate operation with custom Comparator instances.

The Core Idea

When working with streams, you often need to sort data before further processing or collecting results. The sorted() intermediate operation allows you to insert sorting logic directly into your stream pipeline. By passing a Comparator, you control exactly how elements are ordered—just like with List.sort() or Arrays.sort(), but within the fluent stream API.

Think of it like an assembly line where items flow through various stations. The sorted(Comparator) station reorganizes items into a specific order before they continue downstream.

How It Works

The sorted() method is an intermediate operation that returns a new sorted stream. When you provide a Comparator, it uses that logic to determine element order:

List<String> names = List.of("Charlie", "Alice", "Bob");

List<String> sortedNames = names.stream()
    .sorted(Comparator.naturalOrder())
    .collect(Collectors.toList());
// Result: [Alice, Bob, Charlie]

You can use any Comparator—factory methods, custom implementations, or chained comparisons:

List<Person> people = List.of(
    new Person("Alice", 30),
    new Person("Bob", 25),
    new Person("Charlie", 30)
);

List<Person> sorted = people.stream()
    .sorted(Comparator.comparingInt(Person::getAge)
                      .thenComparing(Person::getName))
    .collect(Collectors.toList());
// Sorted by age first, then name

Important Notes

  • sorted() is a stateful operation—it must see all elements before producing output
  • Works seamlessly with reversed(), nullsFirst(), and all Comparator methods you've learned
  • Without arguments, sorted() uses natural ordering (requires Comparable)

Key Takeaway: Use sorted(Comparator) to order stream elements mid-pipeline, leveraging all the powerful Comparator factory methods and chaining techniques for clean, declarative sorting logic.