Skip to lesson

Intermediate vs Terminal Operations and Laziness

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

PipelineDemo.javaJava
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);    }}
Output
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 new Stream; sorted().toList() ends with a terminal operation that builds the result list.
  • marks is 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 a Stream.
  • A source is list.stream(), Stream.of(...) or IntStream.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.

List<Integer> result = marks.stream()
.filter(m -> m >= 40)
.map(m -> m + 5)
.sorted()
.toList();
Quick test in an interview: if the method returns 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.

Order of work for four names with filter then map. Separate loops would filter all four names first, then map the survivors. A stream filters Asha and Bala (dropped), then filters and maps Chetan, then filters and maps Divya, one element at a time.

Example 2 · Laziness and element-by-element order

LazyOrderDemo.javaJava
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);    }}
Output
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: Rakesh goes through filter and then map before Meena is 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

PeekCountDemo.javaJava
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);    }}
Output
--- 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 A never runs. Pipeline 2 ends in count(), and on Java 9 and later the stream knows the size of List.of(...) without visiting the elements, so peek B is skipped too.
  • In pipeline 3, filter makes the size unknown, so count() must walk the elements and peek C runs 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 peek alone prints nothing.
  • The order is per element: element 1 passes every step before element 2 starts.
  • Stateful steps (sorted, distinct) break that order: sorted waits for every element.
  • On Java 9 and later, count() on a sized source can skip peek and map completely.

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.

List<String> log = new ArrayList<>();
List<Integer> fees = List.of(1200, 800, 1500);
fees.stream().filter(f -> {
log.add("F" + f);
return f > 1000;
});
System.out.println(log);
Never put real work inside 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

ShortCircuitDemo.javaJava
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);    }}
Output
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

  • findFirst stops 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 infinite Stream.iterate safe 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, noneMatch stop early.
  • limit(n) and takeWhile (Java 9) stop an infinite stream.
  • On an empty stream allMatch and noneMatch return true, anyMatch returns false.
  • findAny may pick any element on a parallel stream; findFirst keeps 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

SingleUseDemo.javaJava
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");    }}
Output
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 throws IllegalStateException with the exact message interviewers expect you to recognise.
  • The Supplier<Stream<String>> returns a brand-new stream on every get(), 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 a Supplier<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 3

Traps: 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.

ParallelSnip.javaJava
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);    }}
Output
500500 500500
[1, 2, 3, 4, 5]

Example 6 · Find the bug: side effects and changing the source

SideEffectTrapDemo.javaJava
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);    }}
Output
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 log stays empty: count() on a sized source skipped map entirely (Java 9 and later), so the side effect never ran. Code that depends on side effects in map breaks silently.
  • Adding to cart while streaming over it throws ConcurrentModificationException at the end of forEach, after the copies were already added. Build a new list with map(...).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 ArrayList from a parallel stream can lose elements; use toList() or collect(...).
  • 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.

import java.util.List;
public class CountPaid {
public static void main(String[] args) {
List<String> status = List.of("PAID", "FAILED", "PAID");
int paid = 0;
status.stream().forEach(s -> { if (s.equals("PAID")) paid++; });
System.out.println(paid);
}
}

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