Confused on Java Stream Results using peek and findAny

e2rabi :

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
rgettman :

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.

Guess you like

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