How short circuit work in Java streams
Understand how limit() short-circuits and how a stream pipeline executes lazily and element-by-element.
đ Example Code
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");
List<String> result = names.stream()
.filter(name -> {
System.out.println("Filtering: " + name);
return name.length() > 3;
})
.map(name -> {
System.out.println("Mapping: " + name);
return name.toUpperCase();
})
.limit(2)
.collect(Collectors.toList());
System.out.println("Result: " + result);
đ§ What Will Happen?
Even though there are 5 names, only the minimum number of elements needed to satisfy limit(2) will be processed.
đ Expected Output
Filtering: Alice
Mapping: Alice
Filtering: Bob
Filtering: Charlie
Mapping: Charlie
Result: [ALICE, CHARLIE]
â Step-by-Step Explanation
Letâs understand this by simulating how the stream pipeline works.
đ Stream pipeline:
Source â filter â map â limit â collect
Java Streams work by pulling data through this pipeline one element at a time.
đ Iteration 1:
Aliceis passed intofilterâ passes (length > 3)Aliceis passed tomap()â becomesALICE- Collected in result list
â 1 of 2 done
đ Iteration 2:
Bobis passed intofilterâ fails (length <= 3)- Not passed to
maporlimit - Skipped
đ Iteration 3:
Charliepassesfilterâ becomesCHARLIE- Collected
â 2 of 2 done
đ Iteration 4 and 5:
Skipped entirely
Why? Because limit(2) has already been fulfilled â itâs a short-circuiting terminal step.
đĄ So How Does limit() Short-Circuit?
Internally:
limit(n)wraps the downstreamSink(collector)- It counts how many elements have been passed downstream
- Once the limit is reached, it stops requesting more elements from upstream
Itâs like: âIâve got 2 items, Iâm done. Stop pulling more!â
đ Why This Matters
- Efficiency: Even though the source has 5 items, only 3 elements were fully evaluated, and 2 were mapped.
- You save CPU cycles and memory
- It’s especially useful with large datasets, infinite streams, or expensive filters/mappings