Java Stream Count Finished. Why Didn’t Peek Run?
A Java stream can compute count directly from its source and skip peek. Trace cardinality, terminal intent and required side effects before changing the pipeline.
Your Java stream returns the right count, but the code inside peek() appears not to have run. Before chasing the logger or a missing terminal operation, check what result you asked the stream to produce. Counting elements doesn't necessarily require visiting their values.
The Java SE 26 count contract explicitly permits computing the answer directly from the source and skipping the intermediate pipeline. If an action must happen for every element, give that action an explicit execution path. A successful count is evidence about cardinality, not a receipt for callbacks.
This is an AI-prepared, documentation-based explainer, not a personally reproduced incident. Code and outcomes below are illustrative and unexecuted. See the editorial policy.
The terminal operation was there all along
A common first explanation for a quiet stream is laziness: somebody built a pipeline and never invoked a terminal operation. That's worth checking. But this illustrative fragment does have one:
import java.util.ArrayList;
import java.util.List;
List<Integer> values = List.of(12, 24, 36);
List<Integer> visited = new ArrayList<>();
long count = values.stream()
.peek(visited::add)
.count();The callback records visits in a separate list so the example doesn't depend on log levels or console buffering. It is a diagnostic illustration, not a recommended collection technique. Under the documented optimization, the count can be three while the callback isn't invoked and visited stays empty. Those are permitted outcomes derived from the API contract, not output captured from a run.
The revealing clue is the source: a list already knows its size. peek() doesn't add or remove elements. If nothing else in the pipeline makes the count depend on examining them, the implementation can answer the question without taking each value through the inspection point.
The program asked “how many?” The callback hoped it had also asked “please do this to each one.” The stream isn't obliged to honor the second request when it only exists as an incidental side effect.
A correct result can leave an incorrect assumption untouched
This isn't a special promise that peek always gets skipped. The Stream interface permits omitting stages when doing so doesn't change the computation's result. Its count example applies to sequential as well as parallel execution. Switching this example to a sequential stream doesn't turn the callback into a required operation.
The stream package's side-effect rules explain the broader trap. Side effects in intermediate callbacks aren't reliable evidence that required work happened. A mapper that preserves the number of elements can have the same problem if the final question only needs that number.
That matters when the callback does more than print. If it validates records, writes an audit entry or updates an external system, count completing successfully doesn't establish that those obligations were performed. A test asserting only the number can pass while never checking the behavior the application actually needs.
Why a filter can make the symptom disappear
Suppose you add a genuine filter. Now the number of results may depend on the values. The documentation contrasts peek with operations such as filter and flatMap that can change the number of elements. That explains why a small pipeline edit can change what you observe.
It's a useful diagnostic clue, but adding a meaningless filter just to make a callback fire is a fragile repair. You're arranging an incidental traversal instead of expressing the required action. Another source, terminal operation or pipeline change can expose the same assumption later.
Ask three questions during review: can the source report its size, which stages can change the number of results, and does the terminal result actually require the transformed values? Then ask the more important application question: which callback contains work that must happen independently of the result?
Give the required work its own contract
If the requirement is to perform an action on every item, an explicit loop often makes the intent easier to review. For the in-memory collection in this illustration, the structure could be:
for (Integer value : values) {
recordRequiredAction(value);
}recordRequiredAction is an illustrative application function, not a library method supplied by this article. Its failure policy still needs a decision: should the loop stop on the first exception, collect failures, or retry an operation? Explicit iteration makes that obligation visible; it doesn't create transactionality or exactly-once delivery to an external service.
Streams also have forEach and forEachOrdered terminal operations whose purpose is to perform actions. Their ordering and concurrency rules matter. In particular, parallel forEach doesn't promise encounter order, and shared mutable state needs appropriate synchronization. Don't swap one implicit assumption for another.
If the requirement is to obtain transformed values, represent them in the result and consume that result. If it is only to count, keep the count. Separating those intentions is usually clearer than making an observational callback carry the application's business behavior.
| What the code needs | What to review |
|---|---|
| Number of elements | Use the count result; don't treat it as proof of intermediate callback execution. |
| Required per-item action | Use an explicit loop or suitable action-oriented terminal operation, with a defined failure policy. |
| Transformed data | Make the transformed values part of the consumed result. |
| Debug observations | Use peek with awareness that it can observe fewer elements, or none, when the pipeline doesn't need them. |
Test the obligation, not the reassuring number
For a proposed regression check, use a source with a known size and assert the required observable behavior separately from any count. Include the source shapes and terminal operations the application actually uses. Don't write a test that requires peek to be skipped; the API permits the optimization rather than promising an identical strategy for every pipeline.
Likewise, a test that happens to observe the callback today doesn't make it a portable business contract. Tests should protect the design you chose for required work, including its exception handling and ordering, rather than freeze an incidental optimization. These are suggested checks, not tests executed for this explainer.
This is a different Stream boundary from the unmodifiable list returned by Stream.toList(). One concerns execution obligations; the other concerns the result's mutation contract. More related investigations live in the Java archive.
In the next code review, put a mark beside every stream callback that changes something outside the pipeline. For each one, identify the API promise that makes it run. If the only answer is “the count at the end,” move that required work into a contract that actually asks for it.