peek for debugging only
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)peek lets you look at each element as it passes a point in a pipeline, without changing it. It takes a Consumer, an action such as printing, and hands every element on untouched. It exists for debugging, and only for debugging.
What peek does
peek is an intermediate step that looks at each element as it passes by and then hands it on unchanged. It exists mainly to help you see what is happening inside a pipeline while debugging.
A long pipeline gives a wrong answer and you want to see inside it: .peek(s -> System.out.println("after filter: " + s)) prints each element that reaches that point and passes it on unchanged.
Example 1 · peek between steps
import java.util.List;
public class PeekBasicsDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 35, 88);
List<String> result = marks.stream() .peek(m -> System.out.println("source: " + m)) .filter(m -> m >= 40) .peek(m -> System.out.println("after filter: " + m)) .map(m -> "Pass " + m) .peek(s -> System.out.println("after map: " + s)) .toList(); System.out.println(result); }}source: 72 after filter: 72 after map: Pass 72 source: 35 source: 88 after filter: 88 after map: Pass 88 [Pass 72, Pass 88]
What this code does
- Each
peekprints what reaches that point and passes the element on unchanged, so the result is the same as without them. - 35 shows up at
sourcebut neverafter filter. That is exactly how you find which step drops or changes an element.
peek is an intermediate operation, so it runs only when a terminal operation pulls elements. That is the big difference from forEach, which is terminal and ends the pipeline.
Splitting a long pipeline into many List variables would change the code you are debugging. You can put several peek calls between steps, each with its own label. The Java documentation itself says peek exists mainly to support debugging, to see elements as they flow past a certain point.
Using peek to see laziness and element flow
The Stream Basics module said that each element travels through the whole pipeline before the next one starts, and that nothing runs without a terminal operation. With peek you can watch both happen.
- Put a labelled
peekbefore and after each step you want to watch. - Run the pipeline with no terminal operation: nothing prints, because nothing has pulled any elements.
- Add
toList(): the labels print element by element,before 72, after 72, before 35, ..., not step by step. - Add
limit(2)orsorted():limitmakes the prints stop early, andsortedmakes every element print before it and then all of them after it.
Example 2 · Seeing laziness: no terminal operation, then limit
import java.util.List;import java.util.stream.Stream;
public class PeekLazinessDemo { public static void main(String[] args) { List<String> orders = List.of("ORD1", "ORD2", "ORD3", "ORD4", "ORD5");
System.out.println("Pipeline built, no terminal operation:"); Stream<String> pending = orders.stream() .peek(o -> System.out.println(" looking at " + o)); System.out.println(" (nothing printed yet)");
System.out.println("With limit(2) and toList():"); List<String> firstTwo = pending .limit(2) .toList(); System.out.println(" " + firstTwo); }}Pipeline built, no terminal operation: (nothing printed yet) With limit(2) and toList(): looking at ORD1 looking at ORD2 [ORD1, ORD2]
What this code does
- Building the pipeline runs nothing. The
peekonly fires oncetoList()starts pulling elements. limit(2)stops pulling after two elements, so ORD3 to ORD5 are never looked at. Thepeekmakes this short-circuiting visible.
Why peek must not hold real logic
Because peek is only a window, Java is free to skip it. Since Java 9, count() returns the size directly when the source size is known and no step can change the count, so your peek never runs.
Example 3 · Trap: peek before count may not run
import java.util.List;
public class PeekCountDemo { public static void main(String[] args) { List<String> students = List.of("Asha", "Ravi", "Meena");
System.out.println("map and peek, then count:"); long a = students.stream() .map(String::toUpperCase) .peek(s -> System.out.println(" peek " + s)) .count(); System.out.println(" count = " + a);
System.out.println("filter and peek, then count:"); long b = students.stream() .filter(s -> s.length() == 4) .peek(s -> System.out.println(" peek " + s)) .count(); System.out.println(" count = " + b); }}map and peek, then count: count = 3 filter and peek, then count: peek Asha peek Ravi count = 2
What this code does
- In the first pipeline nothing can change the number of elements, so
count()takes the size of the list and skipsmapandpeekentirely (Java 9 and later). - In the second,
filtercan drop elements, socount()must walk the stream and thepeekruns. Whetherpeekruns depends on the other steps, which is why it must never carry real work.
Example 4 · Trap: real work hidden in peek
import java.util.ArrayList;import java.util.List;
record Order(String id, int amount) {}
public class PeekLogicDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("O1", 1200), new Order("O2", 300), new Order("O3", 4500), new Order("O4", 2600));
List<String> smsSent = new ArrayList<>(); List<Order> bigOrders = orders.stream() .filter(o -> o.amount() >= 1000) .peek(o -> smsSent.add(o.id())) .limit(2) .toList(); System.out.println("Big orders shown: " + bigOrders.size()); System.out.println("SMS sent to: " + smsSent);
List<String> smsFixed = new ArrayList<>(); orders.stream() .filter(o -> o.amount() >= 1000) .forEach(o -> smsFixed.add(o.id())); System.out.println("Fixed, SMS sent to: " + smsFixed); }}Big orders shown: 2 SMS sent to: [O1, O3] Fixed, SMS sent to: [O1, O3, O4]
What this code does
- The developer wanted an SMS for every big order and used
peekto "send" it on the way.limit(2)stopped the stream early, so O4 never got its SMS. Nothing failed; a customer simply missed a message. - The fix gives the real work its own pipeline ending in
forEach, which visits every element by contract.
Short-circuiting steps such as limit and takeWhile stop pulling elements early, so a peek before them sees only some elements.
Parallel streams, covered later, may run peek in any order. So if a peek sends an SMS, adds to an audit list or updates a balance, that work may happen for every element, for some, or for none, depending on the rest of the pipeline. Real work belongs in the terminal operation, such as forEach, or in a loop.
Predict the output
Does peek run?
Read the code, then pick what it prints.
Round 1 of 2
peek would change what the program does (apart from debug prints), it holds real logic and must move.Removing debug peeks before code review
Debug prints left in a pipeline flood the server log and slow it down, and a reviewer cannot tell a forgotten debug line from intended behaviour. Remove every debug peek before you commit.
Example 5 · A labelled debug helper that is easy to remove
import java.util.Comparator;import java.util.List;import java.util.function.Consumer;
record Student(String name, int marks) {}
public class DebugHelperDemo { // one place to switch debug output on or off, and one name to search for static <T> Consumer<T> debug(String label) { return x -> System.out.println("[debug] " + label + ": " + x); }
public static void main(String[] args) { List<Student> students = List.of( new Student("Asha", 78), new Student("Ravi", 35), new Student("Meena", 91), new Student("Kiran", 66));
List<String> toppers = students.stream() .filter(s -> s.marks() >= 60) .peek(debug("passed")) .sorted(Comparator.comparing(Student::marks).reversed()) .peek(debug("sorted")) .limit(2) .map(Student::name) .toList(); System.out.println("Toppers: " + toppers); }}[debug] passed: Student[name=Asha, marks=78] [debug] passed: Student[name=Meena, marks=91] [debug] passed: Student[name=Kiran, marks=66] [debug] sorted: Student[name=Meena, marks=91] [debug] sorted: Student[name=Asha, marks=78] Toppers: [Meena, Asha]
What this code does
- Every debug
peekgoes throughdebug(...), so one search fordebug(finds them all before review. The labels show thatsortedwaits for every passing student before releasing any. - After
limit(2)has two students, the thirdsortedelement is never printed. Once the bug is found, delete the twopeeklines; the result does not change.
Two habits make that easy. Give every debug peek a clear label, or route it through one small helper such as debug("after filter"), so a single search finds them all. And for longer sessions, use your IDE's debugger: a breakpoint inside a lambda shows the element without changing the code at all.
Next step
Check your understanding
12 quick questions