Sometimes I want to perform a set of operations on a stream, and then process the resulting stream two different ways with other operations.
Can I do this without having to specify the common initial operations twice?
For example, I am hoping a dup()
method such as the following exists:
Stream [] desired_streams = IntStream.range(1, 100).filter(n -> n % 2 == 0).dup();
Stream stream14 = desired_streams[0].filter(n -> n % 7 == 0); // multiples of 14
Stream stream10 = desired_streams[1].filter(n -> n % 5 == 0); // multiples of 10
It is not possible in general.
If you want to duplicate an input stream, or input iterator, you have two options:
List<>
Suppose you duplicate a stream into two streams s1
and s2
. If you have advanced n1
elements in s1
and n2
elements with s2
, you must keep |n2 - n1|
elements in memory, just to keep pace. If your stream is infinite, there may be no upper bound for the storage required.
Take a look at Python's tee()
to see what it takes:
This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use
list()
instead oftee()
.
For this option to work, you'll probably need access to the inner workings of the stream. In other words, the generator - the part that creates the elements - should support copying in the first place. [OP: See this great answer, as an example of how this can be done for the example in the question]
It will not work on input from the user, since you'll have to copy the state of the entire "outside world". Java's Stream
do not support copying, since it is designed to be as general as possible; for example, to work with files, network, keyboard, sensors, randomness etc. [OP: Another example is a stream that reads a temperature sensor on demand. It cannot be duplicated without storing a copy of the readings]
This is not only the case in Java; this is a general rule. You can see that std::istream
in C++ only supports move semantics, not copy semantics ("copy constructor (deleted)"), for this reason (and others).