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