Java Stream peek() Method
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
// 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.
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() 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.
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);
}
}
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.
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);
}
}
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.
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);
}
}
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.
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(""));
}
}
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
| Method | Kind | Returns | Purpose |
|---|---|---|---|
peek(action) | Intermediate | The same stream elements | Observe elements for debugging |
forEach(action) | Terminal | void | Perform an action for every element |
map(f) | Intermediate | Transformed elements | Change elements |
forEachOrdered(action) | Terminal | void | Action 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
orders.stream()
.peek(orderRepository::save) // may never run, for example with count()
.count();
Use a terminal operation for actions that must happen:
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);
}
}
Saved: [ORD-1, ORD-2]
Other mistakes to avoid
- Changing element state in
peek(), such aspeek(o -> o.setStatus(PAID)); usemap()to produce updated copies. - Leaving
System.out.printlnin 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 andmap()for changes.
9. References
Frequently Asked Questions (FAQ)
Q1. What is peek() used for in Java streams?
peek() is an intermediate operation that runs an action on each element as it passes and returns the same elements. Its documented purpose is debugging: observing elements between pipeline stages.
Q2. Why does my peek() not print anything?
Either the pipeline has no terminal operation, or the library skipped the stage because the result did not need it, for example count() on a stream whose size is known, which on Java 9 and later can be computed without traversing elements.
Q3. What is the difference between peek() and forEach()?
peek() is an intermediate, lazy operation that returns a stream and may be skipped. forEach() is a terminal operation that runs the action for every element and returns void.
Q4. Can peek() modify elements?
It receives the element and could call methods on it, but the stream continues with the same object references. Changing state there is fragile and discouraged; use map() to create modified values.
Q5. Is peek() safe in parallel streams?
It runs on worker threads in any order, so its action must be thread-safe. Printing is safe but the output order will vary.