Skip to content
Preptima
mediumScenarioConceptMidSenior

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.

4 min readUpdated 2026-10-09Target archetype: Enterprise Captive, Product Startup

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

Further reading

Related Topics