需要为初学者解释流中的异常:IllegalStateException [重复]

问题描述 投票:0回答:1

我是 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 lambda collections java-stream
1个回答
0
投票

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

此操作终止/关闭流,因此如果您在关闭时再次尝试任何操作,则会引发异常。

您只需再次创建流即可。

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+" "));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.