liveBook · Manning

Peek

As explained in 100 Java Mistakes and How to Avoid Them

A peek operation is a Stream intermediate operation that applies a supplied Consumer to elements as they pass through the pipeline without changing their values.

peek is an intermediate Stream operation whose Consumer observes elements without changing their values. Treat it as a debugging aid, not as a dependable way to populate external state: execution can be skipped when the pipeline optimizes away elements. section 9.2

A fragile collection side effect

List<String> trimmed = new ArrayList<>(); List<String> trimmedLong = strings.stream() .map(String::trim) .peek(trimmed::add) .filter(s -> s.length() > 10) .limit(5) .toList(); Here, limit(5) can stop traversal before every trimmed element reaches peek, so trimmed may be incomplete. Build trimmed in a separate stream instead. section 9.2

Avoid treating peek as ordinary pipeline logic:

  • Use map, filter, or a collector for transformations and results rather than mutating external collections from an intermediate operation. section 9.2
  • Expect ordering and thread-safety problems when side effects run concurrently through parallelStream(). section 9.2
List<String> trimmed = strings.stream()
  .map(String::trim).toList();
List<String> trimmedLong = trimmed.stream()
  .filter(s -> s.length() > 10).limit(5).toList();

Separate the trimmed result from the filtered-and-limited result so each stream performs a complete, explicit operation. section 9.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains side effects, short-circuiting, parallel execution, and optimization limits without descending into Stream implementation internals.
Examples
Uses trimming, external collection, filtering, limit(5), count, and separate streams to expose incomplete side effects.
What you can do after
Diagnose/debug pipeline traversal with peek and replace fragile side effects using explicit stream operations.
How it connects
Connects peek with map, filter, limit, count, parallel streams, and partitioningBy.

Also explained in

Compare how 3 books explain peek →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.