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:
Alice
is passed intofilter
β passes (length > 3
)Alice
is passed tomap()
β becomesALICE
- Collected in result list
β 1 of 2 done
π Iteration 2:
Bob
is passed intofilter
β fails (length <= 3
)- Not passed to
map
orlimit
- Skipped
π Iteration 3:
Charlie
passesfilter
β 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