Streams: peek is for observing, not for changing state

peek runs only for elements the pipeline actually pulls, and a stream with no terminal operation never runs at all - which is why it is a debugging tool, not a processing step.

Code
var log = new ArrayList<String>();

Stream.of("a", "b", "c").peek(log::add).filter(s -> s.equals("a")).findFirst();
System.out.println("short-circuited, peek saw: " + log);

log.clear();
Stream.of("a", "b", "c").peek(log::add);
System.out.println("no terminal operation, peek saw: " + log);
Output
short-circuited, peek saw: [a]
no terminal operation, peek saw: []
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30