Stream报错:stream has already been operated upon or closed

Stream 有一个特点:只能使用一次

public class StreamUtils {
    
    
    public static void main(String[] args){
    
    
        StreamUtils.useOne();
    }

    public static void useOne(){
    
    
        Stream<Integer> stream= Stream.of(1,2,4,7,8,0,11,33,56);
        stream.filter(num -> num > 3).forEach(num -> Out.out(num));
        stream.filter(num -> num > 10).forEach(num -> Out.out(num));
    }
 }

运行结果:

2022-12-29 18:12:42 4
2022-12-29 18:12:43 7
2022-12-29 18:12:43 8
2022-12-29 18:12:43 11
2022-12-29 18:12:43 33
2022-12-29 18:12:43 56
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed

运行stream.filter(num -> num > 3).forEach(num -> Out.out(num)); 输出大于3的数字,之后在运行stream.filter(num -> num > 10).forEach(num -> Out.out(num)); 报错,因为Stream只能使用一次;

猜你喜欢

转载自blog.csdn.net/qq_15283475/article/details/128486214