Stream Creation in Java

You have already seen that you can turn any collection into a stream with the stream method of the Collection interface. If you have an array, use the static Stream.of method instead.

Stream<String> words = Stream.of(contents.split(“\\PL+”));

// split returns a String[] array

The of method has a varargs parameter, so you can construct a stream from any number of arguments:

Stream<String> song = Stream.of(“gently”, “down”, “the”, “stream”);

Use Arrays.stream(array, from, to) to make a stream from a part of an array.

To make a stream with no elements, use the static Stream.empty method:

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

// Generic type <String> is inferred; same as Stream.<String>empty()

The Stream interface has two static methods for making infinite streams. The generate method takes a function with no arguments (or, technically, an object of the Supplier<T> interface). Whenever a stream value is needed, that function is called to produce a value. You can get a stream of constant values as

Stream<String> echos = Stream.generate(() -> “Echo”);

or a stream of random numbers as

Stream<Double> randoms = Stream.generate(Math::random);

To produce sequences such as 0 1 2 3 . . ., use the iterate method instead. It takes a “seed” value and a function (technically, a UnaryOperator<T>) and repeatedly applies the function to the previous result. For example,

Stream<BigInteger> integers

= Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));

The first element in the sequence is the seed BigInteger.ZERO. The second element is f(seed) which yields 1 (as a big integer). The next element is f(f(seed)) which yields 2, and so on.

To produce a finite stream instead, add a predicate that specifies when the iteration should finish:

var limit = new BigInteger(“10000000”);

Stream<BigInteger> integers

= Stream.iterate(BigInteger.ZERO,

n -> n.compareTo(limit) < 0,

n -> n.add(BigInteger.ONE));

As soon as the predicate rejects an iteratively generated value, the stream ends.

Finally, the Stream.ofNullable method makes a really short stream from an object. The stream has length 0 if the object is null or length 1 otherwise, containing just the object. This is mostly useful in conjunction with flatMap—see Section 1.7.7, “Turning an Optional into a Stream,” on p. 22 for an example.

The example program in Listing 1.2 shows the various ways of creating a stream.

Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *