Search code examples
javajava-8java-streamreusability

How to call multiple terminal operation on a Java stream


I know that whenever we call any terminal method on a stream, it gets closed.

If we try to call any other terminal function on a closed stream it will result in a java.lang.IllegalStateException: stream has already been operated upon or closed.

However, what if we want to reuse the same stream more than once?

How to accomplish this?


Solution

  • 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!