To reuse a stream

Ricky Clarkson ricky.clarkson at gmail.com
Fri Feb 22 12:23:32 PST 2013


Hi,

If I run the following:

IntStream numbers = Streams.intRange(2, Integer.MAX_VALUE);
IntStream primes = numbers.filter(x -> x < 3 ||
numbers.limit(x).noneMatch(y -> x % y == 0));
primes.limit(100).forEach(System.out::println);

I get an IllegalStateException at the forEach call: Stream is already
linked to a child stream, which was a surprise.  I guessed that the problem
is that I'm using the same stream twice recursively.  The following works
fine:

IntStream numbers = Streams.intRange(2, Integer.MAX_VALUE);
IntStream primes = numbers.filter(x -> x < 3 || Streams.intRange(2, x -
1).noneMatch(y -> x % y == 0));
primes.limit(100).forEach(System.out::println);

This seems an odd design, I wouldn't naturally expect such a Stream to have
a problem with concurrent/recursive use.  It means that a Stream is an
object I need to protect/manage the ownership of, like an Iterator, and not
so much like an Iterable, even if the underlying data source is immutable.
 Is this deliberate?  If so will there be another abstraction that can be
used and shared more freely?

Ricky.


More information about the lambda-dev mailing list