Foreach循环

时间:2018-02-09 13:02:40

标签: collections java-8 java-stream

任何人都可以帮助我为什么这个案例会例外吗?

IntStream i = IntStream.of(6,5,7,1, 2, 3, 3);
    IntStream d = i.map(n -> n+1 );
    d.forEach(System.out::print);
    System.out.println();
    System.out.println("Origional Streams" );
    i.forEach(System.out::print);

这是输出。

7682344
Origional Streams
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
at java.util.stream.IntPipeline$Head.forEach(IntPipeline.java:557)

1 个答案:

答案 0 :(得分:0)

看那个

d = i.map(n -> n + 1);

表示流d正在引用流i, 现在forEach是一个终端操作,消耗i的流,也影响了参考d。

enter image description here