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
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 emptyOptional
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 incount()
), 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With