Java 25 (LTS) reference · Stream API

Java Stream sorted() Method

Return a stream sorted by natural order or by a Comparator. The source collection is not changed.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

stream.sorted(comparator)

Parameters

ParameterDescription
comparator optional
Comparator<T>
Optional ordering.

Return value

A new sorted Stream<T>.

Examples

Sorted copies
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(5, 2, 9);
        System.out.println(nums.stream().sorted().toList());
        System.out.println(nums.stream().sorted(Comparator.reverseOrder()).toList());
        System.out.println(nums);
    }
}

Output

[2, 5, 9]
[9, 5, 2]
[5, 2, 9]

Run this on your computer — see “Get Started” for setup.

By length, then alphabetically
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(Stream.of("kettle", "tea", "mug").sorted(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder())).toList());
    }
}

Output

[mug, tea, kettle]

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?