Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused on Java Stream Results using peek and findAny

I'm new to Java's Stream API, and I'm confused on the results of this case:

Stream<String> stream = Stream.of("A","B","C","D");
System.out.println(stream.peek(System.out::println).findAny().get());

This prints:

A
A

Why does it not print:

A
A
B
B
C
C
D
D
like image 319
e2rabi Avatar asked Jan 02 '23 08:01

e2rabi


1 Answers

The findAny method doesn't find all the elements; it finds just one element.

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.

This is a short-circuiting terminal operation.

The stream is not processed until a terminal method is called, in this case, findAny. But the peek method doesn't execute its action on an element until the element is consumed by the terminal action.

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.

The findAny method is short-circuiting, so peek's action will only be called for that element found by findAny.

That is why you only get two A values in the printout. One is printed by the peek method, and you print the second, which is the value inside the Optional returned by findAny.

like image 87
rgettman Avatar answered Jan 13 '23 11:01

rgettman