You do not want.
A Stream is a one-time chain of operations and should never be permanent. Even storing it in the instance field, as in your question, is an indicator of a misunderstanding of its purpose. After applying terminal operation to a thread, this is useless, and threads cannot be cloned. In this case, it makes no sense to remember an unused stream in a field.
Since the only operations offered by Stream associate more operations with the pipeline and finally evaluate it, there is no way to query its state so that it can create an equivalent stream regarding its behavior. Therefore, no storage system can save it. The only thing that the infrastructure can do is move the resulting elements of the stream operation and save them, but this means efficient storage of some Stream collection. In addition, the one-time nature of the Stream also implies that the structure of the vault passing through the stream to store items had a side effect that made the stream unusable at the same time.
If you want to store items, resort to the usual Collection .
On the other hand, if you really want to save the behavior, you will end up saving an instance of the object whose actual class implements the behavior. This still works with Stream , since you can save an instance of a class that has a factory method that creates the desired stream. Of course, you do not actually save the behavior, but a symbolic link to it, but this always happens when you use the OO framework to store behavior, not data.
source share