The Stateful Nature of sorted
You'll learn why sorted() must process the entire stream before producing any output, making it fundamentally different from operations like filter() or map().
Why sorted Is Stateful
When you call sorted() on a stream, it cannot emit even a single element until it has seen every element in the stream. Think of it like organizing a deck of cards: you can't confidently place the "smallest" card in position one until you've checked all the cards to ensure nothing smaller exists.
This is what makes sorted() a stateful operation—it must maintain state about all elements before producing output.
Contrast with Stateless Operations
Operations like filter() and map() are stateless: they can process each element independently and immediately pass it downstream. If you have a million-element stream and use filter(), the first matching element flows through instantly.
With sorted(), those million elements must all be collected, sorted in memory, and then emitted one by one. There's no way around this—sorting inherently requires comparing elements against each other.
Practical Implications
Stream.of(5, 2, 8, 1)
.peek(n -> System.out.println("Before sort: " + n))
.sorted()
.peek(n -> System.out.println("After sort: " + n))
.forEach(n -> {});
You'll see all "Before sort" messages print first (5, 2, 8, 1), then all "After sort" messages in order (1, 2, 5, 8). The sorted() acts as a barrier, accumulating everything before releasing results.
This means sorted() requires memory proportional to the stream size and breaks the ideal stream pattern of one-element-at-a-time processing.
Key Takeaway:
sorted() is a stateful operation that must buffer the entire stream in memory before emitting any elements, making it more expensive than stateless operations like filter() or map().