Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. This is equivalent to:
double result = identity;
for (double element : this stream)
result = accumulator.applyAsDouble(result, element)
return result;
but is not constrained to execute sequentially.
The identity
value must be an identity for the accumulator
function. This means that for all x
,
accumulator.apply(identity, x)
is equal to x
.
The accumulator
function must be an
associative function.
This is a terminal operation.
identity | the identity value for the accumulating function | |
op | an associative, non-interfering, stateless function for combining two values |
sum(), min(), max(), average()
@apiNote Sum, min, max, and average are all special cases of reduction. Summing a stream of numbers can be expressed as:
double sum = numbers.reduce(0, (a, b) -> a+b);
or more compactly:
double sum = numbers.reduce(0, Double::sum);
While this may seem a more roundabout way to perform an aggregation
compared to simply mutating a running total in a loop, reduction
operations parallelize more gracefully, without needing additional
synchronization and with greatly reduced risk of data races.
Diagram: Stream