Video in progress
Explain the difference between intermediate and terminal operations.
An intermediate operation (filter, map, sorted) returns a new stream and doesn't run right away. A terminal operation (collect, forEach, count) produces a result and triggers the whole chain.
📖 Answer
A chain has three parts: a source, several intermediate operations and a single terminal operation at the end.
long count = orders.stream() // source
.filter(o -> o.amount() > 0) // intermediate
.map(Order::customerId) // intermediate
.distinct() // intermediate
.count(); // terminal: it runs here
A simple rule: if the method returns a Stream, it's intermediate; if it returns anything else (List, long, Optional, void), it's terminal.
A chain written without a terminal operation doesn't run at all. For example list.stream().map(x -> { System.out.println(x); return x; }); prints nothing, because there's no terminal operation.
After a terminal operation the stream is closed and can't be used again.
Commonly used terminal operations: toList, collect, forEach, count, reduce, findFirst, anyMatch, min/max.
Sign up to mark studied questions and save your progress.