Stream.of()
Creates a stream from the listed values.
Available since: Java 8
Syntax
static <T> Stream<T> of(T... values)Parameters
| Parameter | Type | Description |
|---|---|---|
| values | T... | 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:
2A 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 closedNotes
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
- Collection.stream() — Creates a stream over the elements of a collection.
- Stream.iterate() — Creates a stream where each element is computed from the previous one.
- IntStream.range() — Creates a stream of integers from a range.
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.