Java Stream sorted()

In this guide, you will learn about the Stream sorted() method in Java programming and how to use it with an example.

1. Stream sorted() Method Overview


The Stream.sorted() method is an intermediate operation that returns a stream consisting of the elements of the original stream, sorted according to their natural order or by a specified comparator. If the stream's elements are not Comparable, a ClassCastException may be thrown during terminal operations.


1. Stream<T> sorted()
2. Stream<T> sorted(Comparator<? super T> comparator)


- comparator: A comparator to be used for comparing stream elements.

Key Points:

- It's an intermediate operation, meaning further operations can be chained after it.

- If no comparator is provided, it assumes that the stream elements are of type Comparable.

- It operates in a stable manner, i.e., equal elements will not be reordered as a result of the sort.

- The operation is stateful as it may need to observe all the elements before producing a result.

- When using parallel streams, the sorted() operation is not as performance-efficient due to the necessity to aggregate the results from different threads.

2. Stream sorted() Method Example

import java.util.Comparator;

public class StreamSortedExample {
    public static void main(String[] args) {
        Stream<String> fruitsStream = Stream.of("Cherry", "Banana", "Apple", "Elderberry", "Date");

        // Using sorted without a comparator (natural order)
        fruitsStream.sorted().forEach(fruit -> System.out.print(fruit + " "));

        System.out.println();  // Print a new line for clarity

        // Using sorted with a comparator (based on string length)
        Stream<String> anotherFruitsStream = Stream.of("Cherry", "Banana", "Apple", "Elderberry", "Date");
                           .forEach(fruit -> System.out.print(fruit + " "));


Apple Banana Cherry Date Elderberry
Date Apple Cherry Banana Elderberry


In the provided example:

1. We first sort a stream of fruit names in their natural order (alphabetic order) and print them.

2. Then, we sort another stream of the same fruit names but this time based on their lengths (using a comparator) and print them.

The output clearly showcases how the elements are sorted in different orders based on the chosen sorting mechanism.