Table of Contents
stream already closed Java 8
stream has already been operated upon or closed in Java 8
You might notice this exception where it states that, “Same stream cannot be used again for processing, You can apply multiple operations on it but you cannot re use it again and again” in Java 8
Lets take an example to reproduce this exception.
Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9); Integer findFirst = stream.filter(i -> (i%2) == 0) .findFirst() .orElse(-1); System.out.println("findFirst : " + findFirst); Integer findAny = stream.filter(i -> (i%2) == 0) // exception is thrown .findAny() .orElse(-1); System.out.println("findAny : " + findAny);
Here it will throw
Exception in thread “main” java.lang.IllegalStateException: stream has already been operated upon or closed.
This exception is being thrown from below piece of code available in constructor of AbstractPipeline where it checks for the variable linkedOrConsumed, if its true then it throws an exception.
We should create different stream every time we perform different operations on it. Let’s re write our above code to avoid above issue.
int [] arr = {1,2,3,4,5,6,7,8,9}; Integer findFirst = Arrays.stream(arr).filter(i -> (i%2) == 0) .findFirst() .orElse(-1); System.out.println("findFirst : " + findFirst); Integer findAny = Arrays.stream(arr).filter(i -> (i%2) == 0) .findAny() .orElse(-1); System.out.println("findAny : " + findAny);