Java Reference
In-Depth Information
List<Integer> someNumbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstSquareDivisibleByThree =
someNumbers.stream()
.map(x -> x * x)
.filter(x -> x % 3 == 0)
.findFirst(); // 9
When to use findFirst and findAny
You may wonder why we have both findFirst and findAny. The answer is parallelism. Finding
the first element is more constraining in parallel. If you don't care about which element is
returned, use findAny because it's less constraining when using parallel streams.
5.4. Reducing
So far, the terminal operations you've seen return a boolean (allMatch and so on), void
(forEach), or an Optional object (findAny and so on). You've also been using collect to combine
all elements in a stream into a List.
In this section, you'll see how you can combine elements of a stream to express more
complicated queries such as “Calculate the sum of all calories in the menu,” or “What is the
highest calorie dish in the menu?” using the reduce operation. Such queries combine all the
elements in the stream repeatedly to produce a single value such as an Integer. These queries
can be classified as reduction operations (a stream is reduced to a value). In functional
programming-language jargon, this is referred to as a fold because you can view this operation
as repeatedly folding a long piece of paper (your stream) until it forms a small square, which is
the result of the fold operation.
5.4.1. Summing the elements
Before we investigate how to use the reduce method, it helps to first see how you'd sum the
elements of a list of numbers using a for-each loop:
int sum = 0;
for (int x : numbers) {
sum += x;
Search WWH ::




Custom Search