sorted() is an intermediate Stream API operation that returns a stream with elements arranged in ascending natural order, or according to a supplied Comparator.
Key Points: • sorted() with no arguments requires the elements to implement Comparable, using their natural ordering. • sorted(Comparator) accepts a custom comparator for reverse order, sorting by a field, or multi-level sorting with thenComparing(). • It's a stateful intermediate operation - the entire stream must be buffered before any element can be emitted downstream. • The original source collection is not modified; sorted() produces a new ordered stream. • Sorting on a parallel stream still produces a deterministic, correctly ordered result, though at some coordination cost.
Example: Given the list [5, 3, 8, 1], calling sorted() produces a stream that yields 1, 3, 5, 8 in that order when collected.
Code Example:
List<Integer> sortedNumbers = numbers.stream()
.sorted()
.collect(Collectors.toList());Interview Tip: A concise interview answer is:
"sorted() returns a stream ordered by natural ordering when the elements are Comparable, or I can pass a Comparator for custom or reverse ordering. It's a stateful operation, meaning the whole stream has to be buffered before elements start flowing downstream."