Java Reference
In-Depth Information
No initial value
There's also an overloaded variant of reduce that doesn't take an initial value, but it returns an
Optional object:
Optional<Integer> sum = numbers.stream().reduce((a, b) -> (a + b));
Why does it return an Optional<Integer>? Consider the case when the stream contains no
elements. The reduce operation can't return a sum because it doesn't have an initial value. This
is why the result is wrapped in an Optional object to indicate that the sum may be absent. Now
see what else you can do with reduce.
5.4.2. Maximum and minimum
It turns out that reduction is all you need to compute maxima and minima as well! Let's see how
you can apply what you just learned about reduce to calculate the maximum or minimum
element in a stream. As you saw, reduce takes two parameters:
An initial value
A lambda to combine two stream elements and produce a new value
The lambda is applied step by step to each element of the stream with the addition operator, as
shown in figure 5.7 . So you need a lambda that, given two elements, returns the maximum of
them. The reduce operation will use the new value with the next element of the stream to
produce a new maximum until the whole stream is consumed! You can use reduce as follows to
calculate the maximum in a stream; this is illustrated in figure 5.8 :
 
Search WWH ::




Custom Search