Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java Stream.peek: observation is not a correctness hook

Last updated: 5 Oct 20264 min read
tutorial
AdvancedBy AITrove Editorial

peek can observe elements that a terminal operation traverses, but its action is not a reliable place for required work.

Traversal determines whether the action runs

An intermediate pipeline is lazy. Creating it does not send audit events, update counters or write records. Even after a terminal call, an implementation may skip stages when it can compute the result without visiting elements. For example, count on a sized source may bypass a peek action.

The program uses collect to force traversal for this particular result. Put required audit writes in an explicit loop or an owned service boundary instead of relying on peek. Short-circuit operations have another reason to visit only a prefix.

Separate inspection from mutation

A diagnostic print may help during local inspection, but it changes observable output and can become expensive in a large pipeline. Lambda capture does not turn shared mutable counters into safe parallel reductions; collect a value instead.

Working program

Java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ShipmentPeekBoundary {
    public static void main(String[] args) {
        Stream<String> pending = Arrays.asList("PK-47", "PK-82").stream()
                .peek(packageId -> System.out.println("visited=" + packageId));
        System.out.println("pipeline-built");
        List<String> packageIds = pending.collect(Collectors.toList());
        System.out.println("collected=" + packageIds.size());
    }
}

Output

Output
pipeline-built
visited=PK-47
visited=PK-82
collected=2

Cost and ownership

This traversal is O(n) time and the collected list is O(n) space. Logging adds I/O cost for each visited element; parallel execution can interleave messages and must not be used to guarantee audit order.

Common Mistakes

  • Do not rely on peek for required writes or validation.
  • Do not assume count will execute every peek action.
  • Do not use a shared mutable counter inside a parallel pipeline.

Read next

Java streams: lazy pipelines and bounded results, stream short circuit, stream parallel encounter order, Java lambdas: function contracts and captured state.

java
streams
stream-peek-side-effects
Storage details