Lecture 3 — Part 3: Streams as Smart Pipelines (Pages 30–40)
Streams are an assembly line: they build a pipeline with lazy intermediate ops (filter/map) and only do work when a terminal op fires. Then they run vertically (one element through the whole pipe), and sometimes they short-circuit (stop early).
Intermediate = lazy (returns Stream)Terminal = triggers work (returns result)Vertical execution = element-by-elementShort-circuit = stop when satisfied
Lab A — The Lazy Robot
Add filter/map all day. Robot does nothing until you call a terminal op.
Robot Status
😴 Sleeping (lazy)
Items: [1, 2, 3, 4, 5]
Pipeline: empty
Terminal needed: forEach()
Output (after terminal)
No results yet (lazy).
Robot Log
01 Robot loaded items: [1,2,3,4,5].
02 Tip: Adding filter/map is INTERMEDIATE (lazy). No work happens yet.
Key idea: intermediate ops are “queued”, terminal op “pulls” elements through.
Lab B — The Vertical Water Slide
One element goes through Filter → Map → Output, then the next one. No batching.
Input Queue
12345
Fixed pipeline for this lab:
filter(x > 2) → map(x * 2) → collect
Vertical Pipe (Stage-by-stage)
Filter Gate
x > 2Status: waiting
Map Gate
x * 2Status: waiting
Output
Collected values appear here.
—
Hit Start to drop elements one-by-one.
Collected Output
none yet
Notice: elements 1 and 2 get blocked by the filter and never reach the map/collect.
Lab C — The Circuit Breaker
Collect scans everything. findFirst short-circuits: “No need to check remaining elements.”
Grid (20 elements) — find the 42
7
13
9
5
18
2
11
40
6
19
3
8
42
1
14
20
4
10
12
15
Pipeline: .filter(x == 42).collect(...)
Collect must exhaust the stream (checks everything).
Scanner Log
Idle
01 Goal: find 42 in a stream pipeline.
02 Mode 1: filter == 42 then collect → checks ALL elements.
03 Mode 2: filter == 42 then findFirst → stops early (short-circuit).
Collect mode: exhaust the stream
Collect must traverse the full stream to build the final list.
What you should conclude
- Intermediate ops (filter, map) are lazy: they build the pipeline.
- Terminal ops (forEach, collect) trigger execution.
- Execution is vertical: element-by-element through the whole pipeline.
- Short-circuiting ops like findFirst stop as soon as they can.
Sign In to Keep Going
You've reached the end of the free preview. Sign in — and upgrade to Plus or Pro — to keep going with DataStructure.
Full Access
Unlock all 13 lessons