The Stream API in Java
A Stream, from java.util.stream, represents a sequence of elements that can be processed through a pipeline of operations — filter, map, sorted, and similar — chained together, without manually writing the equivalent loops by hand. Stream operations split into two kinds: intermediate operations like filter and map return another Stream and are lazy, meaning they don't actually run any processing yet; a terminal operation like collect, count, or forEach is what actually triggers the whole pipeline to execute, all at once, from start to finish.
A Stream isn't a data structure itself and doesn't store any elements of its own — it's a view over some other source, most often a collection, computed on demand. Once a terminal operation has consumed a Stream, that specific Stream object is done and can't be reused or run through again; a fresh one has to be created from the original source to process it again.
Creating a Stream
list.stream() produces a Stream view over a collection's elements, ready for a processing pipeline.
Intermediate operations
filter, map, sorted, and similar each return another Stream, and are lazy, running nothing yet on their own.
Terminal operations
collect, count, forEach, and similar actually trigger the whole chained pipeline to run, all at once.
Streams aren't data structures
A Stream is a view over some other source, computed on demand, storing no elements of its own.
Streams are single-use
Once a terminal operation consumes a Stream, that specific Stream object is done; a fresh one must be created to process the source again.
import java.util.List;import java.util.stream.Collectors; public class StreamDemo { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4, 5); List<Integer> evenSquares = numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .collect(Collectors.toList()); System.out.println(evenSquares); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.