You put logging in peek() to debug a stream, and nothing prints once the pipeline ends in count(). Is the stream broken?
No. Since JDK 9, count() may skip the pipeline entirely when the size is known from the source and no stage adds or removes elements, so peek never runs. Stream laziness means stages run only when the terminal operation needs them, which makes side effects in peek or map unreliable rather than merely bad style.
Answer
Short answer
No, the stream is working as specified. Since JDK 9, count() may compute its answer straight from the source without running the pipeline, when the source knows its size and no stage changes the number of elements. In that case peek is never called, so its logging never prints. Stream laziness means a stage runs only when the terminal operation needs its output, and count() on a list does not need any.
Was this answer helpful?
Likely follow-ups
- A teammate wrote list.stream().map(repo::save).count() to report rows saved. What happened after the JDK upgrade?
- Which intermediate operations keep the element count known, and which ones lose it?
- Why does peek before findFirst log fewer elements than the list holds?
- How would you debug a long stream pipeline without relying on peek at all?
Related questions
- Your Collectors.toMap call passed every test and threw in production. What did the code assume, and what are your options?mediumAlso on streams4 min
- Why would you stream a large file rather than read it into memory, and what is backpressure?mediumAlso on streams4 min
- Streams are lazy until a terminal operation runs. Why does that matter, and when would you make one parallel?mediumAlso on streams5 min
- Walk me through writing your own Collector. What do its four functions do, and what do the characteristics promise the pipeline?hardAlso on streams5 min