This question already has an answer here:
这个问题在这里已有答案:
- Java 8 Streams peek api 4 answers
Java 8 Streams peek api 4 answers
By Java 8 API: peek(Consumer action)
通过Java 8 API:peek(消费者行为)
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
返回由此流的元素组成的流,另外在每个元素上执行提供的操作,因为元素是从结果流中消耗的。
I have the code with Java 8 peek that I cannot understand:
我有Java 8偷看的代码,我无法理解:
The first version:
第一个版本:
IntStream in = IntStream.range(3, 8);
in.peek(System.out::print).map(x->x*2);
I assume that this code would print results from mapping, i.e. 68101214. For some reason this code prints nothing.
我假设此代码将打印映射结果,即68101214.由于某种原因,此代码不打印任何内容。
Second version:
IntStream in = IntStream.range(3, 8);
in.peek(System.out::print).map(x->x*2).boxed().forEach(System.out::print);
This code prints 3648510612714, i.e. one number from the original stream, number after mapping and so forth. What is the logic?
该代码打印3648510612714,即来自原始流的一个数字,映射后的数字等等。逻辑是什么?
1 个解决方案
#1
1
The reason for this is that the first stream does not actually execute.
原因是第一个流实际上没有执行。
On the second stream you are calling forEach
which actually causes the stream to execute.
在第二个流上,您调用的是实际导致流执行的每个流。
You could call .count()
at the end of the first stream and it would run.
您可以在第一个流的末尾调用.count()并运行它。
#1
1
The reason for this is that the first stream does not actually execute.
原因是第一个流实际上没有执行。
On the second stream you are calling forEach
which actually causes the stream to execute.
在第二个流上,您调用的是实际导致流执行的每个流。
You could call .count()
at the end of the first stream and it would run.
您可以在第一个流的末尾调用.count()并运行它。