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

Short-Circuiting Behavior of limit

Understand how limit short-circuits stream processing, stopping upstream operations once n elements are collected.

Short-Circuiting Behavior of limit

You'll learn how limit stops upstream operations early, saving processing time by not evaluating more elements than needed.

The Core Idea

When you use limit(n) in a stream pipeline, it doesn't just control how many elements reach the terminal operation—it actively short-circuits the entire pipeline. Once n elements have been collected, limit tells all upstream operations to stop processing entirely. No more elements are requested from the source, and no more intermediate operations are applied.

Think of it like a factory assembly line with a quota: once you've packaged 10 items, you don't keep manufacturing more parts or running them through inspection. The entire line shuts down.

How It Works

Stream.iterate(1, n -> n + 1)  // Infinite stream: 1, 2, 3, ...
      .peek(n -> System.out.println("Generated: " + n))
      .map(n -> n * 2)
      .peek(n -> System.out.println("Mapped: " + n))
      .limit(3)  // Stop after 3 elements
      .forEach(System.out::println);

Output:

Generated: 1
Mapped: 2
2
Generated: 2
Mapped: 4
4
Generated: 3
Mapped: 6
6

Notice that only three elements flow through the pipeline. Once limit(3) has collected three elements, it signals upstream operations to halt. The infinite iterate doesn't keep generating numbers, and map stops transforming values.

Why This Matters

Without short-circuiting, an infinite stream would run forever. Even with finite streams, short-circuiting improves performance by avoiding unnecessary work on elements that would be discarded anyway.

Key Takeaway: limit(n) is an intermediate short-circuiting operation that stops the entire stream pipeline once n elements pass through, preventing upstream sources and operations from doing unnecessary work.