javalambdacollectionsjava-stream

need an explanation for a beginner about exception in stream: IllegalStateException


Im a beginner in java programming and I just started Streams. I have a problem with this code and I can't understand how to resolve it. I read few existing solutions in the results but I cant understand those complicated codes.

public class LambdaStream{
    public static void main(String[] args) {
        //new list of integers
        List<Integer> list = List.of(1,2,76,23,56,1,78,341,13);
        Stream<Integer> stream = list.stream();
        //new stream with only integers
        Stream<Integer> evens = stream.filter(e->e%2==0);
        
       //i need to print both the lists
        System.out.println("Even numbers in the list are: ");
        evens.forEach(e->System.out.print(e+" "));
        System.out.println();
        System.out.println("Original list is: ");
        stream.forEach(e-> System.out.print(e+" "));
    }
}

I heard that using lambdas multiple times is a problem, then how i can generate another stream which has even numbers. Exception is:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
    at java.base/java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
    at oops.LambdaStream.main(LambdaStream.java:22)

Solution

  • Java Stream has certain operations which are called as "Terminal Operations", forEach being one of them.

    This operations terminates/closes the Stream, hence if you try any operation again on closed, exception is being thrown.

    You can simply create the stream again.

    public class LambdaStream{
        public static void main(String[] args) {
            //new list of integers
            List<Integer> list = List.of(1,2,76,23,56,1,78,341,13);
            Stream<Integer> stream = list.stream();
            //new stream with only integers
            Stream<Integer> evens = stream.filter(e->e%2==0);
    
            //i need to print both the lists
            System.out.println("Even numbers in the list are: ");
            evens.forEach(e->System.out.print(e+" "));
            System.out.println();
            System.out.println("Original list is: ");
            list.stream().forEach(e-> System.out.print(e+" "));
        }
    }