Java Reference ยท Streams and Functional
Java Stream.reduce() method
Reference for Java Stream.reduce(): combine elements into a single value with an identity, an accumulator and a combiner, and know when to use sum or collect.
reduce() folds the elements of a stream into a single value by repeatedly applying an associative combining function. Summing numbers, finding a maximum or concatenating strings are all reductions.
There are three forms. One takes only the function and returns an Optional (the stream may be empty). One adds an identity value that is returned for an empty stream. The third also has a combiner and allows the result type to differ from the element type.
int sum = Stream.of(1, 2, 3).reduce(0, Integer::sum); // 6
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Optional<T> reduce(BinaryOperator<T> accumulator) T reduce(T identity, BinaryOperator<T> accumulator) <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
| Name | Description |
|---|---|
identity |
Starting value; must satisfy combiner(identity, x) == x for every x. |
accumulator |
Associative, stateless function that folds an element into the running result. |
combiner |
Merges two partial results (parallel streams); must be compatible with the accumulator. |
Returns: the reduced value, or an Optional that is empty when the stream was empty (first form). Throws: NullPointerException if the one-argument form's result would be null.
Usage notes
- Associativity is required.
(a op b) op cmust equala op (b op c), or parallel results will differ from sequential ones (in the subtraction example one pass gives -21, but two halves combined give 9). - Identity must be neutral:
0for addition,1for multiplication,""for concatenation. Using10as the "identity" of a sum adds 10 once per partial result in parallel. - Primitive streams have
sum(),min(),max(),average()andsummaryStatistics()that are clearer and avoid boxing. - Do not build collections with
reduce. Each step would copy or mutate shared state; usecollect(). - Strings:
reduce("", String::concat)is O(n squared); useCollectors.joining(). - Empty streams: the identity forms never return null; the one-argument form forces you to handle emptiness through
Optional. - Max and min have dedicated methods,
max(Comparator), that read better thanreduce(BinaryOperator.maxBy(...)).