Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A stream pipeline gives the wrong result and a colleague adds peek(System.out::println) to debug it, but nothing is printed for some stages. Explain why and better ways to debug streams.

peek only runs for elements that actually reach that stage, and only when a terminal operation pulls them through, so a pipeline without a terminal operation prints nothing, a filter before peek hides the elements it rejects, a short-circuiting operation such as findFirst stops after the first match, and count() on a sized source can skip the stages entirely. Better ways to debug are an IDE stream debugger that shows each stage's elements, breakpoints inside lambdas, and breaking the pipeline into named variables or methods that can be tested. peek is meant for debugging, never for business logic.

Background to this question

Adding a print statement is the first thing most of us do when code misbehaves, and with streams it often seems to make things more confusing: some stages print, some do not, and the output order looks strange. This question is common because the confusion comes from not knowing how streams execute, and the answer explains a lot about laziness, short-circuiting and optimisation. In this answer, we will recap how a stream runs, reproduce each case where peek stays silent, see why each happens, and then look at better ways to debug a pipeline and why peek must never carry real work.

1A Quick Recap: Streams Are Lazy and Pull One Element at a Time

Intermediate operations such as filter, map and peek do not do anything when we call them. They only describe a step. The work starts when a terminal operation, such as toList, forEach, count or findFirst, is called, and then elements flow through the whole pipeline one at a time: the first element goes through every stage, then the second, and so on.

peek(action) is an intermediate operation that runs the action on each element as it passes and hands the element on unchanged. So it prints exactly the elements that pass through its position in the pipeline, at the moment they pass. Each silent case below follows from that.

2Case 1: No Terminal Operation

The simplest case is a pipeline that is never run.

Java
Stream<Integer> doubled = Stream.of(1, 2, 3)
.peek(x -> System.out.println("before map: " + x))
.map(x -> x * 2);
// prints nothing: no terminal operation has been called yet
List<Integer> result = doubled.toList();
// before map: 1
// before map: 2
// before map: 3

This often happens when a method builds a stream and returns it, and the caller never consumes it, or consumes it in a branch the test does not reach.

3Case 2: Filters and Short-Circuiting

A peek placed after a filter only sees elements the filter let through. And a short-circuiting terminal operation stops pulling as soon as it has its answer.

Java
Optional<Integer> firstBig = Stream.of(1, 2, 3, 4, 5)
.peek(x -> System.out.println("source: " + x))
.filter(x -> x > 1)
.peek(x -> System.out.println("passed filter: " + x))
.findFirst();
// source: 1
// source: 2
// passed filter: 2
// (3, 4 and 5 are never pulled)
Step throughfindFirst pulls only what it needs
Sourcepeek 1filter x > 1peek 2findFirst
1
1
1 rejected
2
2
2
2: answer found, stop

7 messages in order. Play them, or step through them one at a time.

Elements travel one at a time through every stage; 3, 4 and 5 are never pulled.

Notice the interleaving. Element 1 is printed by the first peek and then rejected by the filter, so the second peek never sees it. Element 2 passes both, findFirst has its answer, and the stream stops. Elements 3 to 5 are never read from the source at all. If the colleague expected to see five lines from each peek, it looks as if two stages are broken, when the pipeline is working exactly as designed.

4Case 3: count() Skips the Pipeline

The most surprising case is an optimisation. Since Java 9, if the source knows its exact size and no stage can change the number of elements, count() returns the size directly without traversing the stream.

Java
long n = List.of("a", "b", "c").stream()
.peek(s -> System.out.println("seen " + s))
.map(String::toUpperCase)
.count();
// 3, and nothing is printed (Java 9 and later)
long m = List.of("a", "b", "c").stream()
.peek(s -> System.out.println("seen " + s))
.filter(s -> !s.isEmpty())
.count();
// seen a, seen b, seen c, then 3: filter can change the count, so elements are traversed

The library is allowed to do this because the stream specification says implementations may skip executing behavioural parameters, our lambdas, when they are not needed to compute the result. The same applies to other optimisations in present and future JDKs. So peek output is never a reliable record of what the pipeline did.

5Better Ways to Debug a Stream

An IDE stream debugger is the most direct tool. IntelliJ IDEA's debugger, for example, can trace the current stream chain at a breakpoint and show, stage by stage, which elements entered and left each operation, including which ones a filter dropped. Other IDEs offer similar views or plugins. Setting a breakpoint inside a lambda also works, with the debugger stopping once per element.

The more lasting fix is to make the pipeline easier to inspect. Long pipelines with inline lambdas are hard to debug for the same reason long methods are. Breaking them into named intermediate results and extracted methods turns each stage into something we can call and test directly.

Java
// Before: one long chain with inline logic
List<Invoice> due = invoices.stream()
.filter(i -> i.status() == OPEN && i.dueDate().isBefore(today) && i.amount().signum() > 0)
.map(i -> i.withPenalty(i.amount().multiply(RATE)))
.toList();
// After: named steps that can each be unit tested
List<Invoice> overdue = invoices.stream().filter(this::isOverdue).toList();
List<Invoice> due2 = overdue.stream().map(this::applyPenalty).toList();
boolean isOverdue(Invoice i) {
return i.status() == OPEN && i.dueDate().isBefore(today) && i.amount().signum() > 0;
}

Now a unit test for isOverdue with one invoice can show exactly which condition is wrong, which is usually where the bug turns out to be. The intermediate list costs a little memory, and once the bug is found the steps can be joined again if that matters.

6Why peek Must Not Hold Business Logic

The Javadoc says peek exists mainly to support debugging. Since we have just seen that peek may be skipped, run for fewer elements than expected, or run in an unpredictable order on a parallel stream, any real work inside it, such as peek(order -> order.markProcessed()) or peek(repo::save), may silently not happen. If an element needs a side effect, do it in forEach at the end, or make the change explicit with map returning a new value, so the behaviour does not depend on how the library optimises the pipeline.

7Follow-up questions

Why does output from different peeks interleave instead of appearing stage by stage?

Because streams process one element at a time through all stages, rather than running each stage over the whole collection before the next. That is what makes laziness and short-circuiting possible. The only exceptions are stateful operations like sorted, which must receive every element before passing any on.

Is peek with a logger in production code acceptable?

For temporary diagnostics, yes, as long as nothing depends on it running. But because it can be skipped, a log from peek is not proof that an element was processed. If we need an audit record, we write it as part of the real processing.

Does peek behave differently on a parallel stream?

Its action runs on whichever thread processes each element, in no particular order, so prints from a parallel stream appear jumbled. If the action touches shared state, it must also be thread-safe.

8Conclusion

In this answer, we saw that peek runs only for elements that reach its position and only when a terminal operation pulls them, so a missing terminal operation, a filter in front of it, a short-circuiting findFirst, or count() on a sized source can each leave it silent. We looked at better tools: IDE stream debuggers, breakpoints in lambdas, and splitting pipelines into named variables and methods that can be unit tested. And we saw why peek must never carry business logic, since the library is free to skip it.

What to say in the interviewAbout 80 seconds aloud

Open with

peek is just an intermediate operation that runs an action on each element as it passes, so it only prints elements that actually reach that point, and only when a terminal operation pulls them.

Then, if they want more

There are a few common reasons it stays silent. If there is no terminal operation, nothing runs at all. If peek sits after a filter, it only sees elements that passed. If the terminal operation short-circuits, like findFirst or anyMatch, the stream stops as soon as it has the answer, so later elements are never even read from the source.

And since Java 9, count on a sized source with no filter can return the size directly without running any of the lambdas, so a peek before it prints nothing. The output also interleaves, because elements travel one at a time through all stages.

To debug properly, I would use the IDE's stream debugger, which in IntelliJ shows each stage's input and output, or breakpoints inside the lambdas. Even better, split the pipeline into named intermediate variables or extract the lambdas into methods like isOverdue, so each step can be unit tested.

And I would make sure peek never holds business logic like saving or marking orders, because the specification lets the library skip it.

About this answer

Last updated
12 November 2026
Versions it names
Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A stream pipeline gives the wrong result and a colleague adds peek(System.out::println)...": https://scrivio-interview-library.netlify.app/java/streams/ce785b8c6d/