Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Stream.peek: practical reference

Stream.peek: practical reference: Stream.peek(action) is a lazy intermediate operation that passes the same elements onward and invokes the Consumer as downstream traversal consumes them.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Stream.peek(...)

Stream.peek(action) is a lazy intermediate operation that passes the same elements onward and invokes the Consumer as downstream traversal consumes them.

Use peek mainly to diagnose values between pipeline stages, and perform required terminal side effects with forEach or forEachOrdered.

Optimization or short-circuiting may omit some or all invocations; in a parallel pipeline the action may run in different threads.

The action must be non-interfering and non-null; it must synchronize any shared state itself, and without a terminal operation it does not run at all.

The terminal toList drives the pipeline: peek prints exactly 1:2:, then map yields [2, 4], so complete stdout is 1:2:[2, 4].

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var result = java.util.stream.Stream.of(1, 2).peek(n -> System.out.print(n + ":")).map(n -> n * 2).toList();
        System.out.println(result);
    }
}

Result

1:2:[2, 4]

The terminal toList drives the pipeline: peek prints exactly 1:2:, then map yields [2, 4], so complete stdout is 1:2:[2, 4].

Sources