Java Reference ยท Streams and Functional
Java Stream.of() and Stream.generate()
Reference for Stream.of(), Stream.ofNullable(), Stream.empty(), Stream.generate() and Stream.builder(): create streams from values or suppliers.
Stream.of() is a static factory that builds an ordered stream from the values you pass. Stream.empty() makes a stream with no elements, Stream.ofNullable() (Java 9) makes a stream of zero or one element, and Stream.generate() makes an infinite, unordered stream by calling a Supplier again and again.
Use these when the data does not already live in a collection or array. For existing collections call collection.stream(); for arrays use Arrays.stream().
Stream<String> s = Stream.of("a", "b", "c"); Stream<Double> noise = Stream.generate(() -> 1.5).limit(3);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
static <T> Stream<T> of(T t) static <T> Stream<T> of(T... values) static <T> Stream<T> ofNullable(T t) // Java 9 static <T> Stream<T> empty() static <T> Stream<T> generate(Supplier<? extends T> s) static <T> Stream.Builder<T> builder()
| Name | Description |
|---|---|
t / values |
The elements, in encounter order. |
s |
Supplies each new element on demand. |
Returns: a sequential stream. of(T) with a null argument throws NullPointerException; of(T...) accepts null elements inside the varargs but throws if the array itself is null.
Usage notes
Stream.of(array)streams the elements only for object arrays. Aint[]is a single object, so you get aStream<int[]>of one element; useIntStream.of(ints)orArrays.stream(ints).generate()is infinite. Always addlimit()or a short-circuiting terminal, or the pipeline never ends.generate()is unordered and the supplier is usually stateful, which makes it a poor fit for parallel streams. For a sequence where each value depends on the previous one useStream.iterate().- Builder:
Stream.Builderis useful when you collect elements in code before streaming; adding afterbuild()throwsIllegalStateException. - Primitive versions:
IntStream.of,LongStream.of,DoubleStream.of, andgenerateon each. - Immutability: these factories create no collection you can modify; the results of
toList()are unmodifiable.
Related
Collection.stream(),Stream.iterate(),IntStream, The Stream API- Lessons: Streams, Varargs