Java流-窥视和跳过 [英] Java streams - peek and skip
问题描述
我正在为考试而学习,我对偷看感到困惑.演示代码:
I'm studying for an exam and I am confused over peek. Demo code:
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
.peek(x -> System.out.print("A" + x))
.skip(6)
.peek(x -> System.out.print("B" + x))
.forEach(x -> System.out.println("C" + x));
输出:
A1A2A3A4A5A6A7B7C7
A8B8C8
A9B9C9
有人可以解释这里发生了什么吗?我所知道的是skip(6)
跳过了前6个元素,而peek将在给定的时刻打印流的值.
Can someone explain what's happening here? All I know is that skip(6)
skips the first 6 elements and peek will print the values of the stream at that given moment.
推荐答案
我认为该示例不必要地令人费解.
I believe that example is unnecessarily obtuse.
这实际上是完全相同的问题,但我相信输出结果会更清楚地说明正在发生的事情.它在流中每项打印一行.
Here's effectively the exact same problem but with output that I believe makes it much more clear what is going on. It prints one line per item in the stream.
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
.peek(x -> System.out.println()) //always prints
.peek(x -> System.out.print("A" + x + " ")) //always prints
.skip(6) //"conditional"
.forEach(x -> System.out.print("B" + x)); //sometimes prints
输出
A1
A2
A3
A4
A5
A6
A7 B7
A8 B8
A9 B9
整数1-6仅使其达到skip
操作的高度,该操作会将其放在地板上.不允许他们达到B
. skip
充当屏障.
Integers 1 - 6 only make it as far as the skip
operation which drops them on the floor. They are not allowed to make it as far as B
. The skip
acts like a barrier.
允许其余项目通过skip
障碍",并使其进入B
.
The remaining items are allowed to pass through the skip
"barrier" and do make it to B
.
这篇关于Java流-窥视和跳过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!