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

sorted: Natural Ordering Without Arguments

Learn how sorted() uses Comparable to sort stream elements in their natural order.

sorted: Natural Ordering Without Arguments

You'll learn how the sorted() operation orders stream elements using their natural Comparable implementation.

The Core Idea

The sorted() intermediate operation, when called without any arguments, relies on the elements themselves to define their ordering. It works by calling the compareTo() method that elements implement through the Comparable interface. This is called natural ordering.

Think of it like asking a group of people to line up "naturally" by height—they already know how to compare themselves without you giving explicit instructions.

How It Works

When you call sorted() on a stream, Java looks for the Comparable<T> implementation in your element type:

List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);
List<Integer> sortedNumbers = numbers.stream()
    .sorted()
    .collect(Collectors.toList());
// Result: [1, 2, 5, 8, 9]

For String elements, natural ordering means alphabetical:

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

Important Constraint

All elements in the stream must be mutually comparable and implement Comparable. If they don't, or if the stream contains null, you'll get a runtime exception.

When to Use

Use sorted() without arguments when:

  • Your elements already implement Comparable naturally (like Integer, String, LocalDate)
  • You want the default ordering behavior
  • You don't need custom sorting logic

Key Takeaway: The sorted() operation with no arguments sorts stream elements using their natural Comparable ordering—it's the simplest way to order elements that already know how to compare themselves.