Reputation: 64
I want to reuse stream object in my method, but when I call second time from supplier I saw stream has already been operated upon or closed error.
private Stream<User> getUserStream(Stream<User> testStream) {
Supplier<Stream<User>> supplierUserStream=()->userStream;
supplierUserStream.get().sorted();
supplierUserStream.get().sorted();// throw exception Stream has already been operated upon or closed
return userStream;
}
I don't want to convert stream to a list. I saw a lot of examples like that.
Supplier<Stream<User>> streamSupplier
= () -> Stream.of(userStream.toArray(size -> new User[size]));
Upvotes: 0
Views: 2003
Reputation: 79105
Look at the message closely (emphasis mine):
java.lang.IllegalStateException: stream has already been operated upon or closed
Since there is no terminal operation in your first statement, your stream has not been closed but has been operated upon which is the reason why you are getting the error when you try to operate on it the second time.
You can change it as follows to get rid of the error:
supplierUserStream.get().sorted().sorted();
However, it will be a kind of hiding a potential problem e.g. if you replace the test call in main
, with the following statement, you will again get the same problem:
getStringStream(Stream.of("Hello", "World")).forEach(System.out::println);
A good way to deal with it can be as suggested by ernest_k:
It can also be resolved by keeping track of derived stream objects. Stream stream = s.get().sorted(); stream = stream.sorted(); return stream.sorted();, to reuse those redundant sort() calls.
Demo:
import java.util.function.Supplier;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
getStringStream(Stream.of("World", "Hello", "Good morning!")).forEach(System.out::println);
}
private static Stream<String> getStringStream(Stream<String> testStream) {
Supplier<Stream<String>> supplierStringStream = () -> testStream;
Stream<String> stream = supplierStringStream.get().sorted();
return stream.sorted();
}
}
Output:
Good morning!
Hello
World
Upvotes: 3