Intermediate vs Terminal Operations and Laziness
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)In an interview you are shown a stream with a peek or a filter and asked "what does this print?". The interviewer is checking one idea: nothing runs until the terminal operation, and each element travels through the steps alone.
The pipeline: source, intermediate, terminal
A stream pipeline is a source, zero or more intermediate operations and exactly one terminal operation. The source supplies the elements, intermediate operations return a new stream, and the terminal operation produces the result.
A source puts elements in, intermediate steps such as filter and map change them, and one terminal step produces the result. This pipeline filters marks, adds grace marks, sorts and collects.
Example 1 · Source, intermediate and terminal steps
import java.util.List;import java.util.stream.Stream;
public class PipelineDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 35, 88, 41, 29, 95);
// source, then two intermediate steps, then the terminal step Stream<Integer> source = marks.stream(); Stream<Integer> passed = source.filter(m -> m >= 40); Stream<Integer> graced = passed.map(m -> m + 5); List<Integer> result = graced.sorted().toList();
System.out.println("Result: " + result); System.out.println("Source unchanged: " + marks);
long toppers = marks.stream().filter(m -> m >= 90).count(); System.out.println("Toppers: " + toppers); }}Result: [46, 77, 93, 100] Source unchanged: [72, 35, 88, 41, 29, 95] Toppers: 1
What this code does
- Each intermediate step (
filter,map) returns a newStream;sorted().toList()ends with a terminal operation that builds the result list. marksis unchanged after the pipeline: streams read their source, they never modify it. The second pipeline is a new stream from the same list.
Model answer, spoken: "A stream pipeline has a source, intermediate operations that return another stream, and one terminal operation that produces the result. Intermediate operations are lazy; the terminal operation triggers the work. A stream never changes its source collection." Revise: Stream pipeline anatomy (opens in a new tab).
Must know:
- Intermediate =
filter,map,flatMap,distinct,sorted,peek,limit,skip. - Terminal =
toList,collect,forEach,reduce,count,min,max,findFirst,anyMatch. - One terminal operation per pipeline; it returns a value or
void, never aStream. - A source is
list.stream(),Stream.of(...)orIntStream.range(...);toList()came in Java 16 and returns an unmodifiable list.
Order of execution
Build the pipeline in order
Tap the parts of this pipeline in the order they appear.
Stream, it is intermediate; anything else is terminal.Laziness: nothing runs without a terminal operation
Lazy evaluation means intermediate operations only record what to do. The work starts when a terminal operation pulls elements through the pipeline, and each element goes through all the steps before the next one starts.
Build a pipeline, print a line, then end it. Watch when the filter and map lines appear, and in which order.
Example 2 · Laziness and element-by-element order
import java.util.List;import java.util.stream.Stream;
public class LazyOrderDemo { public static void main(String[] args) { List<String> names = List.of("Asha", "Rakesh", "Meena", "Om");
System.out.println("Building the pipeline"); Stream<String> pipeline = names.stream() .filter(n -> { System.out.println(" filter " + n); return n.length() > 4; }) .map(n -> { System.out.println(" map " + n); return n.toUpperCase(); }); System.out.println("Pipeline built, nothing has run yet");
List<String> result = pipeline.toList(); System.out.println("Result: " + result); }}Building the pipeline Pipeline built, nothing has run yet filter Asha filter Rakesh map Rakesh filter Meena map Meena filter Om Result: [RAKESH, MEENA]
What this code does
- Nothing prints while the pipeline is built. The work starts only at
toList(), the terminal operation. - The order is per element:
Rakeshgoes throughfilterand thenmapbeforeMeenais even checked. Interviewers call this vertical order; a common wrong answer is all filters first, then all maps.
Example 3 · Predict the output: peek with and without a terminal
import java.util.List;
public class PeekCountDemo { public static void main(String[] args) { List<Integer> fees = List.of(1200, 800, 1500);
fees.stream().peek(f -> System.out.println("peek A " + f)); // no terminal operation System.out.println("--- 1. no terminal: nothing printed above");
long n = fees.stream().peek(f -> System.out.println("peek B " + f)).count(); System.out.println("--- 2. count() = " + n + ", and peek B never ran");
long big = fees.stream() .filter(f -> f > 1000) .peek(f -> System.out.println("peek C " + f)) .count(); System.out.println("--- 3. with filter, count() = " + big); }}--- 1. no terminal: nothing printed above --- 2. count() = 3, and peek B never ran peek C 1200 peek C 1500 --- 3. with filter, count() = 2
What this code does
- Pipeline 1 has no terminal operation, so
peek Anever runs. Pipeline 2 ends incount(), and on Java 9 and later the stream knows the size ofList.of(...)without visiting the elements, sopeek Bis skipped too. - In pipeline 3,
filtermakes the size unknown, socount()must walk the elements andpeek Cruns for the two fees that pass.
Model answer, spoken: "Intermediate operations only record the work. The terminal operation pulls the elements through, one at a time, so each element passes every step before the next one starts." Revise: Lazy evaluation (opens in a new tab).
Must know:
- No terminal operation means no work at all, so
peekalone prints nothing. - The order is per element: element 1 passes every step before element 2 starts.
- Stateful steps (
sorted,distinct) break that order:sortedwaits for every element. - On Java 9 and later,
count()on a sized source can skippeekandmapcompletely.
Predict the output
What gets logged?
Each program records its steps in a list. Pick what it prints.
Round 1 of 3
A pipeline with no terminal operation.
peek. It exists for debugging, and the stream is allowed to skip it.Short-circuiting: findFirst, anyMatch, limit
Short-circuiting means an operation can finish without looking at every element. findFirst, findAny, anyMatch, allMatch, noneMatch and limit stop as soon as the answer is known.
Elements flow one at a time, so a search can stop at the first match. Watch how few elements findFirst and anyMatch look at.
Example 4 · findFirst, anyMatch and limit stop early
import java.util.List;import java.util.Optional;import java.util.stream.Stream;
public class ShortCircuitDemo { public static void main(String[] args) { List<Integer> waitlist = List.of(12, 7, 0, 3, 0);
Optional<Integer> firstConfirmed = waitlist.stream() .filter(w -> { System.out.println("checking WL " + w); return w == 0; }) .findFirst(); System.out.println("Found: " + firstConfirmed.isPresent());
boolean anyLong = waitlist.stream() .peek(w -> System.out.println("anyMatch sees " + w)) .anyMatch(w -> w > 10); System.out.println("Any long waitlist? " + anyLong);
List<Integer> powers = Stream.iterate(1, x -> x * 2).limit(5).toList(); System.out.println("First 5 powers of 2: " + powers); }}checking WL 12 checking WL 7 checking WL 0 Found: true anyMatch sees 12 Any long waitlist? true First 5 powers of 2: [1, 2, 4, 8, 16]
What this code does
findFirststops at the first confirmed ticket (WL 0, the third element). The last two elements are never checked.anyMatch(w -> w > 10)is true after the first element, so it looks at only one.limit(5)makes the infiniteStream.iteratesafe to collect.
filter(...).findFirst() checks only until the first match, and Stream.iterate(1, x -> x * 2).limit(5) makes an infinite stream safe. Revise: findFirst and findAny (opens in a new tab).
Must know:
findFirst,findAny,anyMatch,allMatch,noneMatchstop early.limit(n)andtakeWhile(Java 9) stop an infinite stream.- On an empty stream
allMatchandnoneMatchreturntrue,anyMatchreturnsfalse. findAnymay pick any element on a parallel stream;findFirstkeeps encounter order.
Streams are single-use (Collection vs Stream)
A collection stores elements and can be read many times. A stream stores nothing: it is a lazy, one-time flow of computation over a source, and it can even be infinite.
A second terminal call on the same stream fails. Run this to see the exact error message, then the Supplier fix.
Example 5 · Reusing a stream throws, a Supplier fixes it
import java.util.List;import java.util.function.Supplier;import java.util.stream.Stream;
public class SingleUseDemo { public static void main(String[] args) { List<String> modes = List.of("UPI", "Card", "Cash", "UPI");
Stream<String> s = modes.stream(); System.out.println("Count: " + s.count()); try { System.out.println("Distinct: " + s.distinct().count()); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); }
Supplier<Stream<String>> fresh = () -> modes.stream(); System.out.println("Count: " + fresh.get().count()); System.out.println("Distinct: " + fresh.get().distinct().count()); System.out.println("List still usable: " + modes.size() + " items"); }}Count: 4 Error: stream has already been operated upon or closed Count: 4 Distinct: 3 List still usable: 4 items
What this code does
- After
s.count()the stream is consumed;s.distinct()on it throwsIllegalStateExceptionwith the exact message interviewers expect you to recognise. - The
Supplier<Stream<String>>returns a brand-new stream on everyget(), so each result gets its own pipeline. The list itself can be streamed any number of times.
The fix is to ask the source for a new stream, for example through a Supplier<Stream<T>>. Revise: Streams are single-use (opens in a new tab).
Must know:
- A second terminal call throws
IllegalStateException. - Fix: call
list.stream()again or use aSupplier<Stream<T>>. - Collection = stored, eager, reusable. Stream = not stored, lazy, single-use, can be infinite.
- A collection uses external iteration (your loop); a stream uses internal iteration (the library loops).
Find the bug
Find the reuse bug
Each snippet should work. Tap the wrong line, then check the fix.
Count all the names, then the distinct names.
Round 1 of 3Traps: side effects, changing the source, parallel streams
A side effect is a lambda changing something outside itself, such as adding to a shared list. The stream may skip the lambda, reorder it or run it on several threads, so side effects give wrong or random results.
Lambdas in map and filter should only compute a value. Run the parallel snippet, then see what breaks when a lambda changes something outside.
import java.util.List;import java.util.stream.IntStream;
public class ParallelSnip { public static void main(String[] args) { int seq = IntStream.rangeClosed(1, 1000).sum(); int par = IntStream.rangeClosed(1, 1000).parallel().sum(); System.out.println(seq + " " + par);
List<Integer> kept = IntStream.rangeClosed(1, 5).parallel().boxed().toList(); System.out.println(kept); }}500500 500500 [1, 2, 3, 4, 5]
Example 6 · Find the bug: side effects and changing the source
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;
public class SideEffectTrapDemo { public static void main(String[] args) { List<String> orders = List.of("pen", "book", "bag");
List<String> log = new ArrayList<>(); long n = orders.stream() .map(o -> { log.add(o); // side effect inside map return o.toUpperCase(); }) .count(); System.out.println("count = " + n + ", log = " + log);
List<String> upper = orders.stream().map(String::toUpperCase).toList(); System.out.println("Pure map + toList: " + upper);
List<String> cart = new ArrayList<>(List.of("pen", "book")); try { cart.stream().forEach(item -> cart.add(item + "-copy")); } catch (ConcurrentModificationException e) { System.out.println("Changed the source: " + e.getClass().getSimpleName()); } System.out.println("Cart now: " + cart); }}count = 3, log = [] Pure map + toList: [PEN, BOOK, BAG] Changed the source: ConcurrentModificationException Cart now: [pen, book, pen-copy, book-copy]
What this code does
- The
logstays empty:count()on a sized source skippedmapentirely (Java 9 and later), so the side effect never ran. Code that depends on side effects inmapbreaks silently. - Adding to
cartwhile streaming over it throwsConcurrentModificationExceptionat the end offorEach, after the copies were already added. Build a new list withmap(...).toList()instead of changing the source.
A parallel stream splits the work across the threads of the common fork-join pool: list.parallelStream() or stream.parallel(). Model answer for "When would you use a parallel stream?": "Only for large, CPU-heavy work on a source that splits well, such as an array or ArrayList, with no shared mutable state. I would measure first, because for small lists the thread overhead makes it slower." Revise: Parallel streams (opens in a new tab).
Must know:
- The stream may skip a lambda, run it in a different order, or run it on several threads at once.
- Adding to a shared
ArrayListfrom a parallel stream can lose elements; usetoList()orcollect(...). - Changing the source collection during the pipeline usually throws
ConcurrentModificationException. - For a pure calculation the parallel answer equals the sequential one, and
toList()keeps the original order.
Fix the error
Fix the stream compile errors
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Count the PAID orders.
Error
CountPaid.java:7: error: local variables referenced from a lambda expression must be final or effectively final
status.stream().forEach(s -> { if (s.equals("PAID")) paid++; });
^Next step
Check your understanding
12 quick questions