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

  • A+

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.


List<String> title = Arrays.asList("Java8", "In", "Action");         Stream<String> s =;         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 Source)     at$Head.forEach(Unknown Source)     at com.test.Java8InAction.CH4.TraversableOnlyOnce.main( 


// Filtering unique elements List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);; -> n % 2 == 0).distinct().forEach(System.out::println); -> 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 --> generates (yields) a new stream each time hence doesnt throw a "java.lang.IllegalStateException: stream has already been operated upon or closed".


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