Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding problem regarding operated streams in Java

Let’s say we have the following code

Stream<Integer> ints = Stream.of(1, 2, 3);
    
ints.peek(System.out::println);
    
ints.forEach(System.out::println);

and I run it, I’ll get an exception:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed

But why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First question:

peek is an intermediate operation, so I thought, that it won’t run/start the stream itself? Only forEach does this, so why has the stream already been operated when reaching forEach?

Second question:

I also thought, that the peek method would be discarded, because it returns a new Stream that I do not consider. Like in

String str = "hello world";
str.toUppercase();
str.charAt(0); // <-- h not H

Thank you for your help!

>Solution :

peek is an intermediate operation, which means it performs an action and produces a new Stream. But you’re reusing the same Stream, therefore getting an IllegalStateException.

If you write the code like this, it would work as intended:

Stream<Integer> ints = Stream.of(1, 2, 3);
    
Stream<Integer> ints1 = ints.peek(System.out::println);
    
ints1.forEach(System.out::println);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading