Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 834
Troskyvs Avatar asked Sep 07 '25 03:09

Troskyvs


2 Answers

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.

like image 161
Naman Avatar answered Sep 09 '25 23:09

Naman


peek() is not terminal operation, you need to add any terminal operation to make peek work, e.g.

Arrays.stream("abc".split("")).peek(new Consumer<String>() { //second
    @Override
    public void accept(String s) {
        System.out.println(s);//breakpoint
    }
}).count();
like image 27
Evgeniy Dorofeev Avatar answered Sep 10 '25 01:09

Evgeniy Dorofeev