Java 8, Stream creation - How to ?





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

// split returns a String[] array
Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));

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 stream from a part of an array.
To make a stream with no elements, use the static Stream.empty method:

// Generic type <String> is inferred; same as Stream.<String>empty()
Stream<String> silence = Stream.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—see Section 2.14, “Functional Interfaces,” on page 42). 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 infinite 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), or 1 (as a big integer). The next element is f(f(seed)), or 2, and so on. The static Files.lines method returns a Stream of all lines in a file. The Stream interface has AutoCloseable as a superinterface. When the close method is called on the stream, the underlying file is also closed.To make sure that this happens, it is best to use the Java 7 try-with-resources statement:

try (Stream<String> lines = Files.lines(path)) {
  Do something with lines
}



The stream, and the underlying file with it, will be closed when the try block exits normally or through an exception.

Comments