Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

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.

Thanks for reading!

Donate to the site — we work hard for you.