00:00

Java Stream peek() Method

Last updated:

peek() is a stateless intermediate operation of java.util.stream.Stream, available since Java 8, that returns the same elements unchanged while running a Consumer on each one as it passes. The documentation states its purpose plainly: it exists mainly to support debugging, so you can see elements as they flow past a point in the pipeline.

This tutorial shows how to use peek() to trace a pipeline, why the action may run fewer times than you expect or not at all, and why it should not be used for business logic.

1. Syntax and Method Signature

Stream.java (API)
// java.util.stream.Stream<T> (Java 8)
Stream<T> peek(Consumer<? super T> action)

// primitive versions
IntStream IntStream.peek(IntConsumer action)

The action is a Consumer<? super T>, whose method void accept(T t) receives each element and returns nothing. peek() returns a Stream<T> with exactly the same elements.

Usage
List<String> result = names.stream()
        .filter(n -> n.length() > 3)
        .peek(n -> System.out.println("passed filter: " + n))
        .map(String::toUpperCase)
        .toList();

2. How peek() Works

peek() runs its action at the moment an element passes through it, which is only when a terminal operation pulls the element. Without a terminal operation, nothing is printed. With short-circuiting steps, it runs only for elements that reach it.

The specification allows the library to skip intermediate steps when they cannot change the result. Since Java 9, for example, count() on a sized stream may compute the size directly and never call peek(). In parallel streams, the action may run on any thread and in any order. These rules are why peek() is a debugging tool and not a place for required work.

peek() observes elements between two stages Elements leave filter and pass through peek, which runs a logging action and hands each element on unchanged to map. The terminal operation toList collects the mapped elements. peek is like a window into the pipeline. names.stream() SOURCE filterlength > 3 peeklog, pass on maptoUpperCase toListList<String> TERMINAL STAGES WITH A PEEK WINDOW The action runs only for elements that actually reach peek().
Figure 1: peek() is a window into the pipeline: it sees each element at that point and passes it on unchanged.

3. Java Examples

Example 1: Tracing a pipeline (Java 9+)

See which order amounts pass each step of a discount pipeline.

TracePipeline.java
import java.util.List;
import java.util.stream.Collectors;

public class TracePipeline {

    public static void main(String[] args) {
        List<Integer> amounts = List.of(250, 1800, 640, 3200);

        List<Integer> discounted = amounts.stream()
                .peek(a -> System.out.println("source:    " + a))
                .filter(a -> a > 500)
                .peek(a -> System.out.println("filtered:  " + a))
                .map(a -> a * 9 / 10)
                .peek(a -> System.out.println("discount:  " + a))
                .collect(Collectors.toList());

        System.out.println("Result: " + discounted);
    }
}
Output
source:    250
source:    1800
filtered:  1800
discount:  1620
source:    640
filtered:  640
discount:  576
source:    3200
filtered:  3200
discount:  2880
Result: [1620, 576, 2880]

How it works: The trace shows vertical processing: each amount travels through every stage before the next one starts, and 250 stops at the filter.

Example 2: peek() and short-circuiting (Java 16+)

Find the first overdue invoice and see how many invoices were looked at.

PeekShortCircuit.java
import java.util.List;

public class PeekShortCircuit {

    record Invoice(String id, int daysOverdue) { }

    public static void main(String[] args) {
        List<Invoice> invoices = List.of(
                new Invoice("INV-1", 0), new Invoice("INV-2", 12), new Invoice("INV-3", 40));

        String firstOverdue = invoices.stream()
                .peek(i -> System.out.println("checking " + i.id()))
                .filter(i -> i.daysOverdue() > 0)
                .map(Invoice::id)
                .findFirst()
                .orElse("none");

        System.out.println("First overdue: " + firstOverdue);
    }
}
Output
checking INV-1
checking INV-2
First overdue: INV-2

How it works: findFirst() stops the pipeline after INV-2, so peek() never sees INV-3. The action runs only for elements that actually flow.

Example 3: peek() may not run at all (Java 9+)

Count elements of a list with and without a filter, both with a peek that prints.

PeekSkipped.java
import java.util.List;

public class PeekSkipped {

    public static void main(String[] args) {
        List<String> files = List.of("a.csv", "b.json", "c.csv");

        long all = files.stream()
                .peek(f -> System.out.println("peek (no filter): " + f))
                .count();
        System.out.println("count = " + all);

        long csv = files.stream()
                .filter(f -> f.endsWith(".csv"))
                .peek(f -> System.out.println("peek (after filter): " + f))
                .count();
        System.out.println("count = " + csv);
    }
}
Output
count = 3
peek (after filter): a.csv
peek (after filter): c.csv
count = 2

How it works: In the first pipeline the size is known, so on Java 9 and later count() returns it without traversing the elements, and the peek() action never runs. After a filter(), the size is unknown and the elements must flow. Never rely on peek() side effects.

Example 4: Collecting debug information in a test (Java 16+)

In a unit test, record which values entered the mapping step to check a bug, then assert on them.

PeekInTest.java
import java.util.ArrayList;
import java.util.List;

public class PeekInTest {

    public static void main(String[] args) {
        List<String> seenByMapper = new ArrayList<>();

        List<Integer> lengths = List.of("alpha", "", "gamma", "pi").stream()
                .filter(s -> !s.isEmpty())
                .peek(seenByMapper::add)          // debug-only capture in a sequential test
                .map(String::length)
                .toList();

        System.out.println("Lengths:        " + lengths);
        System.out.println("Seen by mapper: " + seenByMapper);
        System.out.println("Empty string reached the mapper? " + seenByMapper.contains(""));
    }
}
Output
Lengths:        [5, 5, 2]
Seen by mapper: [alpha, gamma, pi]
Empty string reached the mapper? false

How it works: Capturing elements into a list is acceptable in a sequential test to understand behaviour. In production code, the result should come from the terminal operation, not from a side effect of peek().

4. Real-World Use Cases

  • Debugging: print or log elements between stages to find where a value is lost or changed.
  • Learning: visualise laziness, vertical processing and short-circuiting, as in the examples above.
  • Metrics in tests: count how many elements reach an expensive step while tuning a pipeline.

5. Important Points

  • Not guaranteed to run: the library may skip it when the result does not need the elements.
  • Runs lazily: nothing happens without a terminal operation.
  • Order and threads: in parallel streams the action can run concurrently, so shared state must be thread-safe.
  • Do not mutate elements: changing a mutable element in peek() works by accident and is easy to break.
  • Remove it before release, or use a logger at debug level.

6. peek() vs Related Methods

MethodKindReturnsPurpose
peek(action)IntermediateThe same stream elementsObserve elements for debugging
forEach(action)TerminalvoidPerform an action for every element
map(f)IntermediateTransformed elementsChange elements
forEachOrdered(action)TerminalvoidAction in encounter order, even in parallel

If you need the action to run for every element, use a terminal forEach(); see forEach().

7. Common Mistakes and Best Practices

Using peek() for real work

Wrong
orders.stream()
      .peek(orderRepository::save)    // may never run, for example with count()
      .count();

Use a terminal operation for actions that must happen:

ForEachForActions.java
import java.util.ArrayList;
import java.util.List;

public class ForEachForActions {

    public static void main(String[] args) {
        List<String> saved = new ArrayList<>();
        List<String> orders = List.of("ORD-1", "ORD-2");

        orders.forEach(saved::add);          // stands in for repository.save(...)

        System.out.println("Saved: " + saved);
    }
}
Output
Saved: [ORD-1, ORD-2]

Other mistakes to avoid

  • Changing element state in peek(), such as peek(o -> o.setStatus(PAID)); use map() to produce updated copies.
  • Leaving System.out.println in production pipelines.
  • Expecting peek() without a terminal operation to print anything.

8. Summary

  • peek() runs an action on elements as they pass and returns them unchanged.
  • It is meant for debugging; the library may skip it when the result does not need the elements.
  • It runs lazily and only for elements that actually flow past it.
  • Use forEach() for required actions and map() for changes.

9. References