findAny

The findAny() method returns an arbitrary (nondeterministic) element from the stream. For example, the following snippet of code will return an element from the preceding list:

Optional<String> anyMelon = melons.stream()
.findAny();

if (!anyMelon.isEmpty()) {
System.out.println("Any melon: " + anyMelon.get());
} else {
System.out.println("No melon was found");
}
Notice that there is no guarantee that it will return the same element at each execution. This statement is true especially in the case of parallelizing the stream.

We can combine findAny() with other operations as well. Here's an example:

String anyApollo = melons.stream()
.filter(m -> m.equals("Apollo"))
.findAny()
.orElse("nope");

This time, the result will be nope. There is no Apollo in the list, and so the filter() operation will produce an empty stream. Furthermore, findAny() will return an empty stream as well, so orElse() will return the final result as the specified string, nope.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.200.3