Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.of()

Creates a stream from the listed values.

Available since: Java 8

Syntax

static <T> Stream<T> of(T... values)

Parameters

ParameterTypeDescription
valuesT...The stream elements.

Return value

Stream<T>A stream of the given values.

Examples

A stream without a collection:

void main() {
    long count = Stream.of("red", "green", "blue").filter(c -> c.length() > 3).count();
    IO.println(count);
}

Output:

2

A stream can be consumed only once:

void main() {
    Stream<Integer> s = Stream.of(1, 2, 3);
    IO.println(s.count());
    try {
        s.count();
    } catch (IllegalStateException e) {
        IO.println(e.getMessage());
    }
}

Output:

3
stream has already been operated upon or closed

Notes

For numbers there are primitive streams without boxing: IntStream.of(1, 2, 3), IntStream.range(). Stream.empty() creates an empty stream and Arrays.stream(array) a stream over an array.

See also

Related recipes

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.