Reusing streams

    Stream<String> stream = asList("a", "b").stream();
    stream.forEach(t -> System.out.println("s1: " + t));
    stream.forEach(t -> System.out.println("s2: " + t));

s1: a
s1: b
Exception in thread “main” java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at com.sabre.ticketing.emd.mt.MyListFlatMap.main(MyListFlatMap.java:32)

Note that exception is thrown from the line #3 since the stream has been already used in the line #2. So cannot reuse it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s