The Plain Picture#
A factory conveyor belt (the same picture as Unix pipes in The Linux Command Line Ch 5): items come from a source, pass through stations — a sieve, a painter, a sorter — and are packed into a box at the end. You describe the stations; the belt moves the items.
The Real Names#
A stream is a sequence of elements you process with a pipeline of operations. It does not store the elements — it describes a computation over a source (a collection, an array, a range of numbers, lines of a file).
A pipeline has three parts:
SOURCE INTERMEDIATE OPERATIONS TERMINAL OPERATION
students.stream() → .filter(...) .sorted(...) .map(...) → .toList()
(where items come from) (each returns a new stream; LAZY) (produces the result; triggers the work)Intermediate operations (
filter,map,sorted,distinct,limit,flatMap…) return another stream and do nothing until a terminal operation runs (Ch 7).Terminal operations (
toList,collect,count,sum,forEach,reduce,findFirst,anyMatch…) produce a result or side effect and close the stream.Streams don't modify the source, and a stream can only be used once:
Stream<String> once = Stream.of("x");
once.count();
once.count(); // IllegalStateException: stream has already been operated upon or closedStyle: declarative (say what you want) rather than imperative (say how, step by step, with loops and temporary lists).
Check yourself
3 questionsName the three parts of a stream pipeline.
Show answerHide answer
Source, intermediate operations, terminal operation.
Does a stream store data? Does it change its source?
Show answerHide answer
No and no.
What happens if you call two terminal operations on the same stream?
Show answerHide answer
The second throws IllegalStateException — streams are single-use.