Java 8 Streams API Stream Creation

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

Empty Stream

Stream<String> empty = Stream.empty();

From Collections

Java 8 Collections expose a new stream() method that returns a stream.

Numeric Ranges

Specialized primitive interfaces IntStream and LongStream expose static range() and rangeClosed() that return a sequential ordered specialized stream with values in the specified range.

IntStream is = IntStream.range(1, 11);

From Values

The Stream class exposes static of() that builds a Stream instance from one argument or a variable list of arguments:

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

In the first case we'll get one element stream, and in the second, the stream will has as many elements as arguments. Of course, this API is practical to use for a small number of elements. To create a stream for a larger array, or when we need a stream of primitive types, see From Arrays below.

From Arrays

Arrays.stream() creates a stream from an array.

https://docs.oracle.com/javase/10/docs/api/java/util/Arrays.html#stream(T%5B%5D)
public static <T> Stream<T> stream(T[] array);

Arrays.stream() is better than Stream.of() when we need a primitive stream, because it will produce a specialized stream instead of autoboxing primitives into Java objects.

From Nullable

Since Java 9.

static <T> Stream<T> ofNullable(T t);
Stream<String> values = Stream.of("config", "home", "user").flatMap(key -> Stream.ofNullable(System.getProperty(key)));

From Files

Many static methods in java.nio.file.Files return a stream.

Note that the associated I/O resources must be closed to avoid leaks, and the streams are auto-closable, so the following pattern may be used:

try(Stream<String> stream = Files.lines(new File(...).toPath())) {

    stream.forEach(...);
}
catch(IOException e) {

    // ...
}

From Functions

Streams can be created from functions, which may result in infinite streams. Specialized streams can also be created from functions.

Stream.iterate()

Stream.iterate() should be used when you need to produce a sequence of successive values, where a value depends on the previous one:

static <T> Stream<T> iterate​(T seed, UnaryOperator<T> f);

The UnaryOperator<T> function receives the current value and returns the next value, calculated based on the current value:

(current-value) -> { return next-value; }
static <T> Stream<T> iterate​(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)

Stream.generate()

static <T> Stream<T> generate​(Supplier<? extends T> s)