Java: Consumer interface in a stream doesn't work as expected

Troskyvs :

I've got 2 statements, I expected that they should "print" same result:

Arrays.stream("abc".split("")).forEach(System.out::println);//first
Arrays.stream("abc".split("")).peek(new Consumer<String>() {//second
    @Override
    public void accept(String s) {
        System.out.println(s);//breakpoint
    }
});

In fact, the first statement will print

a
b
c

Ok, but the second statement prints nothing. I tried to set a breakpoint in the line of "//breakpoint" inside IntelliJ, but it wasn't hit.

So how should I change the second statement to use "peek" as it create a new stream while processing every element using "Consumer"?

Thanks a lot.

Naman :

Stream.peek, as stated in the javadocs of the API as well, is meant mainly for debugging purposes and performing any update operations on the stream during the peek operation is not recommended.

For example, you can verify the intermediate stream state with the following code and what it eventually results in:

Arrays.stream("acb".split(""))
      .peek(System.out::println) // print a  c  b 
      .sorted()
      .forEach(System.out::println); // print a  b  c

In general, this operation is an intermediate operation wouldn't be executed unless and terminal operation is performed on the stream as mentioned in the Stream operations and pipelines section of the docs and that is exactly the reason why your first statement will print.

Note: Though as suggested in a few other answers, the action within peek is not invoked in the cases when its able to optimize the result for some short-circuiting operations like findFirst etc.

In cases where the stream implementation is able to optimize away the production of some or all the elements (such as with short-circuiting operations like findFirst, or in the example described in count()), the action will not be invoked for those elements.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86859&siteId=1
Recommended