How to call multiple terminal operation on a Java stream
Yes its a big NO in Java 8 streams to reuse a stream
For example for any terminal operation the stream closes when the operation is closed. But when we use the Stream in a chain, we could avoid this exception:
Normal terminal operation:
Stream<String> stream =
Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> s.startsWith("a"));
stream.anyMatch(s -> true); // ok
stream.noneMatch(s -> true); // exception
But instead of this, if we use:
Supplier<Stream<String>> streamSupplier =
() -> Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> s.startsWith("a"));
streamSupplier.get().anyMatch(s -> true); // ok
streamSupplier.get().noneMatch(s -> true); // ok
Here the .get()
"constructs" a new stream and NOT reuse whenever it hits this point.
Cheers!