In java 8, once stream is terminated by a termination operation, then the stream cannot be re-used. Hence, you have to re-create the same stream again in some cases.
To overcome this drawback, before all termination operations, you may create a stream supplier followed by all intermediate operations. Thus, you may re-achieve the stream for different termination operations.
Each call to get() constructs a new stream.
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
No comments:
Post a Comment