0

Can Anyone help me why this case is giving the exception?

IntStream i = IntStream.of(6,5,7,1, 2, 3, 3);
    IntStream d = i.map(n -> n+1 );
    d.forEach(System.out::print);
    System.out.println();
    System.out.println("Origional Streams" );
    i.forEach(System.out::print);

Here is Output.

7682344
Origional Streams
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.IntPipeline$Head.forEach(IntPipeline.java:557)
Holger
  • 285,553
  • 42
  • 434
  • 765
Waseem Saeed
  • 85
  • 1
  • 13
  • this will be closed as a duplicate I bet... `d.forEach` and then `i.forEach` calling two terminal operations... – Eugene Feb 09 '18 at 13:04
  • i also d.close(); also gives the same error. There is Terminal operations on both IntStreams i think they are thread safe. – Waseem Saeed Feb 09 '18 at 13:07
  • 1
    yes there are two terminal operations.. you are calling `forEach` two times. what does thread safety has to do with this? – Eugene Feb 09 '18 at 13:12
  • @Eugene can you please suggest me a solution for this. Don't you think there are two Streams. ? Each run independently ?? – Waseem Saeed Feb 09 '18 at 13:48
  • 2
    you create a supplier for this... `Supplier sup = () -> IntStream.of(6, 5, 7, 1, 2, 3, 3);` and call `sup.get()` to get a new `IntStream` all the time – Eugene Feb 09 '18 at 13:57
  • Eugene is right, stream is designed for consuming once. – holi-java Feb 09 '18 at 14:08
  • Eugene That is what i was looking for. Thanks, Mate! – Waseem Saeed Feb 10 '18 at 06:35

1 Answers1

0

look that

d = i.map(n -> n + 1);

means that the stream d is taking the reference of the stream i, now forEach is a terminal operation, consuming the stream of i, affecting the ref on d too.

enter image description here

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97