findFirst

If findAny() returns any element, findFirst() returns the first element from the stream. Obviously, this method is useful when we are interested only in the first element of a stream (for example, the winner of a contest should be the first element in a sorted list of competitors).

Nevertheless, if the stream has no encounter order, then any element may be returned. According to the documentation, streams may or may not have a defined encounter order. It depends on the source and intermediate operations. The same rule applies in parallelism as well.

For now, let's assume that we want the first melon in the list:

Optional<String> firstMelon = melons.stream()
.findFirst();

if (!firstMelon.isEmpty()) {
System.out.println("First melon: " + firstMelon.get());
} else {
System.out.println("No melon was found");
}

The output will be as follows:

First melon: Gac

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

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

This time, the result will be nope since the filter() will produce an empty stream.

The following is another problem with integers (just follow the right-hand comments to quickly discover the flow):

List<Integer> ints = Arrays.asList(4, 8, 4, 5, 5, 7);

int result = ints.stream()
.map(x -> x * x - 1) // 23, 63, 23, 24, 24, 48
.filter(x -> x % 2 == 0) // 24, 24, 48
.findFirst() // 24
.orElse(-1);
..................Content has been hidden....................

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