Intermediate Short-Circuiting: limit Operation
You'll learn how limit() caps stream size to stop processing unnecessary elements early.
The Core Idea
The limit(n) operation is an intermediate short-circuiting operation that restricts a stream to at most n elements. Once that limit is reached, the stream stops pulling elements from its source—even if more elements are available. This prevents downstream operations from wasting time processing data you don't need.
Think of it like filling a bucket: once you have the 5 gallons you need, you turn off the hose. You don't let the entire reservoir drain just because it's available.
Why limit() Short-Circuits
Unlike regular intermediate operations (like map() or filter()), which must potentially examine every element, limit() can say "I have enough" partway through. When combined with lazy evaluation, this means:
- Infinite streams become usable: You can take the first 10 elements from an endless generator.
- Performance boost: Processing stops as soon as the limit is satisfied.
- Efficient with expensive sources: If reading elements is costly (database queries, network calls),
limit()prevents fetching more than necessary.
How It Works in a Pipeline
Stream.iterate(1, n -> n + 1) // infinite: 1, 2, 3, 4, ...
.limit(5) // stop after 5 elements
.forEach(System.out::println); // prints 1 through 5 only
Without limit(), this would never terminate. With it, only 5 iterations occur and only 5 elements flow through forEach().
Key Takeaway: limit(n) is your tool for capping stream size, enabling safe use of infinite streams and optimizing performance by halting processing once enough elements have been produced.