Collection.stream()
Creates a stream over the elements of a collection.
Available since: Java 8
Syntax
default Stream<E> stream()Return value
Stream<E>A new stream over the collection elements.
Examples
A chain of operations over a list:
void main() {
List<String> names = List.of("Anna", "Oleg", "Ivan", "Alla");
List<String> result = names.stream()
.filter(n -> n.startsWith("A"))
.map(String::toUpperCase)
.toList();
IO.println(result);
IO.println(names);
}Output:
[ANNA, ALLA]
[Anna, Oleg, Ivan, Alla]Notes
A stream does not store data and does not change the source collection. Intermediate operations (filter, map, sorted) are lazy and run only when a terminal operation (toList, count, forEach, collect) is called. A stream is single-use: reusing it throws IllegalStateException. Map has no stream — use map.entrySet().stream().
See also
- Stream.of() — Creates a stream from the listed values.
- Stream.filter() — Keeps only the stream elements that match a condition.
- Stream.map() — Transforms every element of a stream.
- Stream.toList() — Gathers stream elements into an unmodifiable list.
In the tutorial
- What a stream is — The Java Stream API — the source, intermediate and terminal operations, creating streams, lazy evaluation and why a stream can be used only once.