Using Stream StreamSupplier

Nishant Kumar :

I'm using following code to reuse Stream but getting

java.lang.IllegalStateException: stream has already been operated upon or closed

Code

public static void main(String[] args) {

    try {
        String[] array = { "a", "b", "c", "d", "e" };
        Stream<String> ss = Stream.of(array);
        Supplier<Stream<String>> streamSupplier = () -> ss;

        long count = streamSupplier.get().count();
        // get new stream
        streamSupplier.get().forEach(x -> System.out.println(x));

        // get another new stream

        System.out.println(count);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Lino :

Don't assign Stream.of(array) to an intermediate variable, just return it directly in the Supplier:

Supplier<Stream<String>> streamSupplier = () -> Stream.of(array);

That is because previously you would just always supply the same reference when calling supplier.get() but in fact you wanted to return a new Stream.

Also as @Eugene suggested, using Arrays.stream() over Stream.of() is preferred. As the latter is a varargs method, but just delegates to the former.


Also your current approach can be simplified using the Stream.peek() method:

long count = Arrays.stream(array)
    .peek(System.out::println)
    .count();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74116&siteId=1