Lazy evaluation and element flow
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A stream does not run step by step over the whole list. It takes one element, pushes it through every step of the pipeline, and only then takes the next one, and it stops as soon as the terminal operation has its answer.
One element at a time, all the way through
Lazy evaluation means a stream does no work until a terminal operation asks for a result, and then each element passes through all steps one at a time.
Most beginners picture a pipeline like a set of separate loops: filter checks every element and builds a list, then map changes every element of that list, then the result is built. That picture is wrong, and it leads to wrong guesses about output.
- The terminal operation asks the stream for its next element.
- The source hands over one element, and it moves through every intermediate step in order.
- A step like
filtermay drop it; then the stream goes back to the source for the next one. - If it survives every step, the terminal operation uses it, then asks for the next element.
- This repeats until the source is empty or the terminal operation already has its answer.
Example 1 · The wrong picture: separate loops
import java.util.ArrayList;import java.util.List;
public class TwoLoopsDemo { public static void main(String[] args) { List<String> names = List.of("Asha", "Chetan", "Divya");
System.out.println("Separate loops (not how a stream runs):"); List<String> kept = new ArrayList<>(); for (String n : names) { System.out.println(" filter " + n); if (n.length() > 4) { kept.add(n); } } for (String n : kept) { System.out.println(" map " + n); }
System.out.println("Stream (one element at a time):"); names.stream() .filter(n -> { System.out.println(" filter " + n); return n.length() > 4; }) .forEach(n -> System.out.println(" map " + n)); }}Separate loops (not how a stream runs): filter Asha filter Chetan filter Divya map Chetan map Divya Stream (one element at a time): filter Asha filter Chetan map Chetan filter Divya map Divya
What this code does
- The two loops filter every name first and keep a middle list
kept; only then does the second loop start. That is the picture many beginners have of a stream. - The stream interleaves the lines: Chetan is filtered and handled before Divya is filtered. It needs no middle list at all.
The real flow is like one loop whose body holds all the steps. The first element goes to filter. If it passes, it goes straight on to map and then to the terminal operation. Only after that does the second element enter. No list is built between the steps. This also means an element dropped by filter never reaches map. The work after a filter runs only for the elements that pass it.
Tracing a pipeline with print statements
You can see the real order by putting a print inside each lambda, such as System.out.println("filter: " + n). The output then shows exactly which step touched which element, and when.
Example 2 · Tracing filter, map and forEach
import java.util.stream.Stream;
public class TraceFlowDemo { public static void main(String[] args) { Stream.of("Asha", "Bala", "Chetan", "Divya") .filter(n -> { System.out.println("filter: " + n); return n.length() > 4; }) .map(n -> { System.out.println("map: " + n); return n + " (" + n.length() + ")"; }) .forEach(s -> System.out.println("forEach: " + s)); }}filter: Asha filter: Bala filter: Chetan map: Chetan forEach: Chetan (6) filter: Divya map: Divya forEach: Divya (5)
What this code does
- Chetan goes through
filter,mapandforEachbefore Divya even enters. Each element finishes the whole pipeline before the next one starts. - Asha and Bala fail the filter, so
mapnever sees them. There is no moment where all four names are filtered first.
Read such a trace from top to bottom: each element's lines appear together, step after step, before the next element's lines start. Use prints only to learn or to debug, and remove them afterwards. The Transforming Streams module shows peek, a step made for this kind of debugging.
Trace the code
Trace one element at a time
Variables
- n
- Asha
Output
filter: Asha
Line 7The first element, Asha, enters filter. The pipeline pulls one element at a time.
count() may skip the steps entirely when it can work out the size from the source. A print inside map followed by count() can then print nothing. Add a filter, or end with toList(), when you trace.Short-circuiting: stopping early
A short-circuiting operation can finish without looking at every element. findFirst() is one: as soon as one element reaches it, it has its answer and the stream stops pulling. The rest of the source is never read.
Example 3 · findFirst stops at the first match
import java.util.List;
public class FindFirstDemo { public static void main(String[] args) { List<Integer> marks = List.of(45, 67, 93, 88, 99, 71);
int firstTopper = marks.stream() .filter(m -> { System.out.println("checking " + m); return m > 90; }) .findFirst() .orElse(-1); System.out.println("First mark above 90: " + firstTopper);
int perfect = marks.stream() .filter(m -> m == 100) .findFirst() .orElse(-1); System.out.println("First mark of 100: " + perfect); }}checking 45 checking 67 checking 93 First mark above 90: 93 First mark of 100: -1
What this code does
- Only 45, 67 and 93 are checked. Once 93 reaches
findFirst, the answer is known, so 88, 99 and 71 are never read. - When nothing matches, every element is checked and
orElse(-1)supplies the fallback value. Short-circuiting saves work only when an answer turns up early.
Example 4 · limit stops after n elements
import java.util.List;
public class LimitDemo { public static void main(String[] args) { List<Integer> rollNumbers = List.of(101, 102, 103, 104, 105, 106, 107, 108);
List<String> firstBatch = rollNumbers.stream() .map(r -> { System.out.println("preparing hall ticket " + r); return "HT-" + r; }) .limit(3) .toList();
System.out.println("First batch: " + firstBatch); }}preparing hall ticket 101 preparing hall ticket 102 preparing hall ticket 103 First batch: [HT-101, HT-102, HT-103]
What this code does
mapcomes beforelimit, yet it runs only three times. After the third ticket passeslimit(3), the stream stops pulling from the source.- Five roll numbers are never read. With a separate-loops picture you would expect eight "preparing" lines.
findFirst() returns an Optional, a box that may be empty when nothing matched. .orElse(-1) opens the box and gives -1 when it is empty; the Optional module covers it fully. anyMatch stops early in the same way. limit(n) is an intermediate operation that also short-circuits. Once n elements have passed it, it tells the stream to stop, so earlier steps run only as often as needed.
Why laziness saves work on large data
A web server writes a log: a text file with one line for every event, often millions a day. Finding the first line that mentions timeout with filter(...).findFirst() reads lines only until the first match.
Example 5 · Real-world: the first timeout in a server log
import java.util.List;
public class LogSearchDemo { public static void main(String[] args) { List<String> log = List.of( "10:00 ok GET /home", "10:01 ok GET /results", "10:02 slow GET /results", "10:03 timeout GET /results", "10:04 ok GET /home", "10:05 timeout POST /pay", "10:06 ok GET /home");
String firstTimeout = log.stream() .filter(line -> { System.out.println("read: " + line); return line.contains("timeout"); }) .findFirst() .orElse("no timeout today");
System.out.println("Answer: " + firstTimeout); }}read: 10:00 ok GET /home read: 10:01 ok GET /results read: 10:02 slow GET /results read: 10:03 timeout GET /results Answer: 10:03 timeout GET /results
What this code does
- The stream reads lines only until the first timeout, line 4 of 7. On a real log with millions of lines and an early match, almost all the reading is saved.
- This is the same saving as a
forloop withbreak, but the pipeline states the goal directly: keep timeouts, take the first.
If it is line 40, the other lines are never checked. Without laziness, filter would check all the lines and build a big list before findFirst could pick the first one.
Laziness gives the same saving as a loop with break, without writing the break. Laziness also rewards good step order. Put cheap filter steps before costly map steps, so the costly work runs only on the elements that survive.
Trap: sorted waits for every element
A few intermediate operations cannot pass an element on at once. sorted() must see all the elements before it knows which one comes first.
Such an operation is called stateful: it keeps memory of the elements it has seen.
Example 6 · Trap: sorted() collects everything first
import java.util.stream.Stream;
public class SortedBarrierDemo { public static void main(String[] args) { Stream.of("Kabir", "Asha", "Diya") .filter(n -> { System.out.println("filter: " + n); return true; }) .sorted() .forEach(n -> System.out.println("forEach: " + n)); }}filter: Kabir filter: Asha filter: Diya forEach: Asha forEach: Diya forEach: Kabir
What this code does
sorted()cannot hand on any name until it has seen all of them, so everyfilterline prints first. Then the names leavesortedin order, one at a time.sortedis stateful: it remembers the elements it has seen. Around such steps the trace looks like separate loops; everywhere else, elements flow one at a time.
sorted() collects every element, sorts them, and only then sends them on one by one. In a trace, every step before sorted runs for all elements first, then every step after it runs. Do not mistake this for the normal flow; it happens only around stateful steps like sorted.
Predict the output
Where does the flow wait?
Read the pipeline, then pick what it prints.
Round 1 of 2
Next step
Check your understanding
12 quick questions