Java Reference ยท Streams and Functional
Java Stream.peek() method
Reference for Java Stream.peek(): watch elements flow through a pipeline for debugging, why it may not run, and why it is not for side effects.
peek() is an intermediate operation that passes every element through unchanged and calls a Consumer on it along the way. Its documented purpose is debugging: seeing which elements reach a certain stage and in what order.
Because streams are lazy and optimizing, the consumer runs only for elements that are actually pulled through, and the implementation may skip it entirely when it can compute the result another way.
List<Integer> r = Stream.of(1, 2, 3) .peek(n -> System.out.println("before: " + n)) .map(n -> n * 2) .toList();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Stream<T> peek(Consumer<? super T> action)
| Name | Description |
|---|---|
action |
Called for each element as it passes. Should not modify the element or the source. |
Returns: a stream with the same elements.
Usage notes
- Debugging only. Use it to print or log; do not rely on it for required side effects. Use
forEachfor work that must happen. - May not run: since Java 9,
count()on a stream with a known size skips the pipeline, so thepeekin the second example'scount()does not print. Do not count on it either way. - Per-element order: each element travels through all stages before the next one starts (except across
sorted(), which buffers), so the output interleaves as in the first example. - Parallel streams: the consumer can run on several threads; its output order is not deterministic and must be thread-safe.
- Mutating inside
peek(for exampleperson.setName(...)) is legal for mutable elements but fragile and discouraged. - A debugger is often better: IntelliJ's "Trace Current Stream Chain" shows each stage without code changes.
- Primitive streams have their own
peektakingIntConsumeretc.