java – Copy a stream to avoid “the stream has already been used or closed”

cyclops-react a library I contribute to, has a static method that will allow you to duplicate a stream (and returns a stream tuple jOOλ).

    Stream stream = Stream.of(1,2,3);
    Tuple2,Stream> streams =  StreamUtils.duplicate(stream);

See comments, there is a performance penalty that is incurred when using the duplicate on an existing Stream. A better performing alternative would be to use Streamable: –

There is also a Streamable (lazy) class which can be constructed from Stream, Iterable or Array and played multiple times.

    Streamable streamable = Streamable.of(1,2,3);;;

AsStreamable.synchronizedFromStream (stream) – can be used to create a Streamable that will idly populate its back-up collection, so that it can be shared between threads. Streamable.fromStream (stream) does not incur any synchronization overhead.

Leave a comment