Friday, 24 May 2019

Reusing Stream in Java 8


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:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...