Lesson · Stream API
Stream basics: a lazy pipeline, not a collection
14 min readBasics
A stream is a one-use view over a source of elements. You describe what should happen, nothing runs until a terminal operation asks for a result, and each element travels the whole pipeline before the next one starts.
What a stream is, and what it is not
A stream is not storage. It does not hold elements, it pulls them from a source (a collection, an array, a file, a generator) and pushes them through the operations you declared. The source is left untouched; a stream never mutates the list it came from.
The second half of the definition is the one that changes how you design with it: a stream is consumed exactly once. After a terminal operation, the pipeline is finished; reusing the stream object is an error, not a reset.
List<String> names = List.of("ada", "grace", "edsger", "linus"); // build a pipeline: nothing has run yet Stream<String> pipeline = names.stream() .filter(n -> n.length() > 4) .map(String::toUpperCase); // terminal operation: now, and only now, elements flow List<String> result = pipeline.collect(Collectors.toList());
Anatomy: source, intermediate, terminal
Every pipeline has three parts. The source produces elements, any number of intermediate operations describe transformations, and exactly one terminal operation runs the show and produces a value or a side effect.
Intermediate operations return another stream, which is why you can chain them. The terminal returns something else entirely (a list, a number, an Optional, or nothing at all).
names.stream() // source .filter(n -> n.length() > 4) // intermediate: keeps grace, edsger, linus .map(String::toUpperCase) // intermediate: GRACE, EDSGER, LINUS .sorted() // intermediate: EDSGER, GRACE, LINUS .collect(Collectors.toList()); // terminal: produces the list
Laziness, precisely
Building a pipeline runs nothing. You can assemble one, print between every line, and nothing happens until the terminal operation executes. That is what lets streams read the entire dataset only when needed, and why a pipeline without a terminal does nothing at all.
When the terminal runs, elements flow differently than most people first assume: each element passes through the whole pipeline before the next element enters. Filter then map means element one is filtered, mapped, and only then element two is fetched. That single detail explains short-circuiting (limit, findFirst) and why peek prints in source order.
Stream<String> lazy = names.stream().peek(n -> System.out.println("peek: " + n)); System.out.println("built, nothing printed"); lazy.forEach(n -> { }); // terminal: the peeks now print, in source order
Pipeline flow · one element at a time
source
filter > 4
map upper
collect
0 pulled
uppercase only if it got past the filter
The pipeline is built: filter (length > 4) then map (uppercase) then collect. Nothing has run. Laziness means every one of these lines just described intent.
Where streams come from
Collections and arrays are the everyday sources; generators and file readers matter as soon as the data stops fitting in a list.
- Collections: list.stream(), set.stream(), map.entrySet().stream().
- Arrays and values: Arrays.stream(array), Stream.of(a, b, c), Stream.empty().
- Ranges (primitive): IntStream.range(1, 5) and rangeClosed, covered in the primitive streams lesson.
- Generators: Stream.iterate(1, n -> n + 1) and Stream.generate(supplier) produce infinite streams that must be paired with limit or a short-circuiting terminal.
- Files: Files.lines(path) streams a file line by line, lazily, without loading it whole.
The single-use rule
A stream carries its own state: which elements have been consumed and how far the pipeline got. Once a terminal operation consumes it, the object is spent. The error is loud and comes with an unusually clear message, which is worth seeing once so you recognize it in production logs.
Stream<String> once = names.stream(); once.count(); once.count(); // java.lang.IllegalStateException: // stream has already been operated upon or closed
Need to process the same data twice? Create two streams from the same source. The source is reusable; the stream object is not.
Vertical, not horizontal
Stage-by-stage processing (all elements filtered, then all mapped) is what loops feel like, but streams process element-by-element through the entire pipeline. That is why limit can stop upstream work early, and why side effects in peek appear interleaved in source order rather than grouped by operation.
Interview angles
What is the difference between a stream and a collection?+
A collection stores elements; a stream computes over them. Streams are lazy, single-use views that never modify the source, while collections are reusable data structures with their own mutability rules.
What does lazy mean for a stream pipeline?+
Intermediate operations only record what should happen. Work begins at the terminal operation, and elements then flow one at a time through the whole pipeline. A pipeline with no terminal operation does nothing.
How many terminal operations can a stream have?+
Exactly one. After the terminal completes, the stream is consumed; calling another operation on it throws IllegalStateException with the message that the stream has already been operated upon or closed.
What order do elements flow through filter and map?+
Each element goes through all stages before the next element is pulled. For filter then map, element one is tested and mapped, then element two is fetched, and so on. This vertical processing is what enables short-circuiting.
Can a stream outlive the method that created it?+
It can be stored in a field or returned, but that is usually a design smell: it may already be consumed, it holds a reference to the source, and callers cannot tell how far it has run. Return streams only when the API contract is a one-shot pipeline.