Skip to content
Tutorials Center
My learning

Topics

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().

Java
Stream<String> s = Stream.of("a", "b", "c");
Stream<Double> noise = Stream.generate(() -> 1.5).limit(3);

Try it

Java Of, empty and ofNullable

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.

Java generate() and builder()

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

Java
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. A int[] is a single object, so you get a Stream<int[]> of one element; use IntStream.of(ints) or Arrays.stream(ints).
  • generate() is infinite. Always add limit() 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 use Stream.iterate().
  • Builder: Stream.Builder is useful when you collect elements in code before streaming; adding after build() throws IllegalStateException.
  • Primitive versions: IntStream.of, LongStream.of, DoubleStream.of, and generate on each.
  • Immutability: these factories create no collection you can modify; the results of toList() are unmodifiable.