需要为初学者解释流中的异常:IllegalStateException

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

我是 java 编程的初学者,我刚刚开始使用 Streams。这段代码有问题,我不明白如何解决它。我在结果中阅读了很少的现有解决方案,但我无法理解那些复杂的代码。

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+" "));
    }
}

我听说多次使用 lambda 是一个问题,那么我如何生成另一个具有偶数的流。 例外是:

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)

Java Stream 有一些被称为“终端操作”的操作,forEach 就是其中之一。

此操作 terminates/closes Stream,因此如果您在关闭时再次尝试任何操作,则会抛出异常。

您只需重新创建流即可。

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+" "));
    }
}