Java streams - peek and skip

冷暖自知 提交于 2020-06-18 02:44:00

问题


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));

Output:

A1A2A3A4A5A6A7B7C7
A8B8C8
A9B9C9

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.


回答1:


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

Output

A1 
A2 
A3 
A4 
A5 
A6 
A7 B7
A8 B8
A9 B9

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.

The remaining items are allowed to pass through the skip "barrier" and do make it to B.




回答2:


The way you printed it was sort of complicated. Imho, it was easier to see by placing a newline at the beginning of the first print statement.


      Stream.of(1, 2, 3, 4, 5, 6).peek(x -> System.out.print("\nA" + x)).skip(
            1).peek(x -> System.out.print("B" + x)).forEach(
                  x -> System.out.print("C" + x));

Produces


A1
A2B2C2
A3B3C3
A4B4C4
A5B5C5
A6B6C6

Clearly a personal preference. It just shows the first one printed by itself and the rest in sequence as they should be.



来源:https://stackoverflow.com/questions/59327869/java-streams-peek-and-skip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!