Java 8 – Once Stream is consumed and operated giving error, but in another case its not

  • A+
Category:Languages

I am new to Java 8 and looking to understand the difference between the two scenarios. I know that once a stream is operated and consumed then stream cant be reused again it will give an error.

Scenario-1:

List<String> title = Arrays.asList("Java8", "In", "Action");         Stream<String> s = title.stream();         s.forEach(System.out::println);         s.forEach(System.out::println); // THIS WILL GIVE ERROR - streams has been already operated and closed. 

When I run this, I get below error... which is fair.

Java8 In Action Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed     at java.util.stream.AbstractPipeline.sourceStageSpliterator(Unknown Source)     at java.util.stream.ReferencePipeline$Head.forEach(Unknown Source)     at com.test.Java8InAction.CH4.TraversableOnlyOnce.main(TraversableOnlyOnce.java:12) 

Scenario-2:

// Filtering unique elements List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4); numbers.stream().forEach(System.out::println); numbers.stream().filter(n -> n % 2 == 0).distinct().forEach(System.out::println); numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println); 

Here also I have operated stream and closed the terminal operation, then why I did not get any error?

 


The two calls to s.forEach utilise the same stream hence the exception in the first example whereas the call to the stream() method --> numbers.stream() generates (yields) a new stream each time hence doesnt throw a "java.lang.IllegalStateException: stream has already been operated upon or closed".

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: