Source, intermediate and terminal operations
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every stream pipeline has three parts: a source that supplies values, zero or more intermediate operations that check or change them, and exactly one terminal operation that produces the result. Knowing which part a method belongs to tells you what it returns and when it runs.
The three parts of every pipeline
An intermediate operation, such as filter or map, returns a new stream and runs lazily; a terminal operation, such as collect or count, produces the result and runs the pipeline.
Think of how answer sheets are handled after an exam. The pile of sheets is the source. Checking them, keeping the passed ones and writing marks are the steps in between. The final result list put up on the notice board is the end result.
Example 1 · Labelling the three parts
import java.util.List;
record Order(String id, int amount, boolean paid) {}
public class ThreePartsDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("A101", 450, true), new Order("A102", 1200, false), new Order("A103", 780, true), new Order("A104", 2300, true));
List<String> paidIds = orders.stream() // source .filter(Order::paid) // intermediate .filter(o -> o.amount() > 500) .map(Order::id) .toList(); // terminal
System.out.println("Paid orders above Rs. 500: " + paidIds); }}Paid orders above Rs. 500: [A103, A104]
What this code does
- One source, three intermediate steps and one terminal step. Each intermediate step returns a stream, so the next dot can follow it.
toList()is the terminal operation: it returns aList<String>, which is what the variable holds. A102 is unpaid and A101 is too small, so they never reachmap.
A stream pipeline has the same shape. The source is where values come from, such as orders.stream(). An intermediate operation is a step in the middle, such as filter or map; a pipeline can have none or many. The terminal operation is the last step, such as count() or toList(), and it turns the flow into a result.
- Source:
list.stream(),Arrays.stream(arr),Stream.of(...),text.lines(). - Intermediate:
filter,map,sorted,distinct,limit,skip. - Terminal:
count,toList,forEach,anyMatch,findFirst,sum(on anIntStream). - Exactly one terminal operation, always last.
Order of execution
Order of a pipeline
Tap the parts in the order they are written.
Intermediate returns a stream; terminal returns a result
The quickest test is the return type. An intermediate operation takes a stream and returns a new Stream, so you can call another step on it. That is why the dots can keep going: .filter(...).map(...).filter(...).
Example 2 · Every intermediate step returns a new Stream
import java.util.List;import java.util.stream.Stream;
public class StepTypesDemo { public static void main(String[] args) { List<String> cities = List.of("Pune", "Goa", "Delhi", "Agra", "Chennai");
Stream<String> source = cities.stream(); Stream<String> longNames = source.filter(c -> c.length() > 3); Stream<Integer> lengths = longNames.map(String::length); List<Integer> result = lengths.toList();
System.out.println("Same object after filter? " + (source == longNames)); System.out.println("Lengths: " + result); }}Same object after filter? false Lengths: [4, 5, 4, 7]
What this code does
- Writing each step into its own variable shows the types:
filterkeepsStream<String>,mapchanges it toStream<Integer>, and only the terminaltoList()gives aList. source == longNamesisfalse:filterbuilt a new stream object instead of changing the old one. Normally you chain the calls and never name the middle streams.
Example 3 · Different terminal operations, different results
import java.util.List;
public class TerminalResultsDemo { public static void main(String[] args) { List<Integer> marks = List.of(55, 92, 38, 100, 71);
long passed = marks.stream().filter(m -> m >= 40).count(); List<Integer> toppers = marks.stream().filter(m -> m >= 90).toList(); boolean perfect = marks.stream().anyMatch(m -> m == 100);
System.out.println("count() -> long: " + passed); System.out.println("toList() -> List: " + toppers); System.out.println("anyMatch() -> boolean: " + perfect); System.out.print("forEach() -> void: "); marks.stream().filter(m -> m < 40).forEach(m -> System.out.println(m)); }}count() -> long: 4 toList() -> List: [92, 100] anyMatch() -> boolean: true forEach() -> void: 38
What this code does
- Each pipeline opens a fresh stream from
marksand ends with a different terminal operation, so each gives a different kind of result. anyMatchanswers a yes-or-no question, andforEachreturns nothing: it only runs an action on each value. The Terminal Operations module covers all of them in depth.
A terminal operation returns something that is not a stream: a long from count(), a List from toList(), a boolean from anyMatch(), or nothing at all (void) from forEach(). After it runs, the pipeline is finished and the stream is closed. A lambda is not a clue. filter and forEach both take a lambda, but filter is intermediate and forEach is terminal.
Nothing runs until the terminal operation
Intermediate operations do no work when you call them. They only record a step in the plan, like writing a recipe without cooking. This is called lazy evaluation: work is done only when its result is needed.
Example 4 · Nothing runs until the terminal operation
import java.util.List;import java.util.stream.Stream;
public class NothingRunsYetDemo { public static void main(String[] args) { List<String> names = List.of("Asha", "Bala", "Chetan", "Divya");
Stream<String> pipeline = names.stream() .filter(n -> { System.out.println(" checking " + n); return n.length() > 4; }); System.out.println("Pipeline built. Nothing checked yet.");
long longNames = pipeline.count(); System.out.println("Names longer than 4 letters: " + longNames); }}Pipeline built. Nothing checked yet. checking Asha checking Bala checking Chetan checking Divya Names longer than 4 letters: 2
What this code does
- The
filterlambda prints a line every time it checks a name. When the pipeline is built, it prints nothing, becausefilteronly records the step. - The checks happen only when
count(), the terminal operation, asks for a result. That is lazy evaluation.
Example 5 · Mistake: a pipeline with no terminal operation
import java.util.ArrayList;import java.util.List;
public class NoTerminalDemo { static String capitalise(String n) { return n.substring(0, 1).toUpperCase() + n.substring(1); }
public static void main(String[] args) { List<String> names = new ArrayList<>(List.of("aarav", "diya", "kabir"));
names.stream().map(n -> capitalise(n)); // result thrown away System.out.println("After the first try: " + names);
List<String> fixed = names.stream() .map(n -> capitalise(n)) .toList(); System.out.println("With toList(): " + fixed); }}After the first try: [aarav, diya, kabir] With toList(): [Aarav, Diya, Kabir]
What this code does
- The first pipeline has no terminal operation, so
mapnever runs. Even if it did, a stream never writes back intonames, so the list keeps its small letters. - The fix ends the pipeline with
toList()and keeps the new list in a variable. The second line shows the capitalised names;namesitself is still unchanged.
The terminal operation is the one that asks for a result. Only then does the stream start pulling values from the source and pushing each one through the steps. The next lesson traces this flow in detail. So a pipeline with no terminal operation does nothing at all. names.stream().map(n -> n.toUpperCase()); compiles, runs and changes nothing: no value is read, and names is untouched. Many IDEs warn that the result is ignored; read that warning as "you forgot the terminal operation".
Formatting long pipelines
A pipeline with three or more steps is easier to read with one step per line. Keep the source on the first line, start every following line with the dot, and indent those lines one level further.
Example 6 · Formatting: one step per line
import java.util.List;
record Result(String name, String subject, int marks) {}
public class FormattingDemo { public static void main(String[] args) { List<Result> results = List.of( new Result("Aarav", "Maths", 81), new Result("Diya", "Physics", 74), new Result("Kabir", "Maths", 29), new Result("Meera", "Maths", 93), new Result("Rohan", "Maths", 35));
// hard to read: every step on one line List<String> cramped = results.stream().filter(r -> r.subject().equals("Maths")).filter(r -> r.marks() >= 35).map(r -> r.name() + ": " + r.marks()).toList();
// easy to read: one step per line List<String> mathsPasses = results.stream() .filter(r -> r.subject().equals("Maths")) .filter(r -> r.marks() >= 35) .map(r -> r.name() + ": " + r.marks()) .toList();
System.out.println(cramped); System.out.println(mathsPasses); }}[Aarav: 81, Meera: 93, Rohan: 35] [Aarav: 81, Meera: 93, Rohan: 35]
What this code does
- Both pipelines are the same code and give the same list. The second one reads as a list of steps: Maths only, passed only, name and marks, as a list.
- Starting each line with the dot makes the steps line up, and a good result name,
mathsPasses, says what the list holds.
Each line then reads as one sentence of the task: from the orders, keep the paid ones, keep the big ones, take the id, make a list. A reviewer can check one line at a time, and a version-control diff shows exactly which step changed. Name the result variable after its meaning, such as bigPaidOrderIds, not list2. If a lambda grows to several lines, move it into a small method with a clear name and call it with a method reference.
Next step
Check your understanding
11 quick questions