Java Stream reduction operations¶
In the Java Stream API, reduction operations (also known as fold operations) process a sequence of elements into a single summary result.^[600-developer__java__java8__java8.md] The primary method for this is reduce, which combines elements iteratively using an accumulator function.^[600-developer__java__java8__java8.md]
The reduce operation offers several overloaded signatures to handle different reduction scenarios.^[600-developer__java__java8__java8.md]
Variants¶
Optional Reduction¶
The most basic form takes an accumulator function and returns an Optional result.^[600-developer__java__java8__java8.md] This variant is used when there is no initial value, meaning the result may be empty if the stream is empty.
// Reduces stream to sum: (x, y) -> x + y
nums.stream().reduce((x, y) -> x + y).ifPresent(System.out::println);
Reduction with Identity¶
This form accepts an initial value, known as the identity, and the accumulator.^[600-developer__java__java8__java8.md] The identity value serves as the starting point and the default result if the stream is empty.
// Sum starting at 100
nums.stream().reduce(100, (x, y) -> x + y);
For numerical streams, methods like summingInt, summingLong, and summingDouble provide specialized reduction implementations via Collectors.1^[600-developer__java__java8__java8.md]
Reduction with Combiner¶
A third variant accepts three arguments: identity, accumulator, and combiner.2^[600-developer__java__java8__java8.md] The combiner is used to combine results from partial reductions, which is necessary for parallel streams to aggregate results from different threads.
// Combines elements with a different type accumulator
nums.stream().reduce("Foo", (x, y) -> x + y, (x, y) -> x + y);
Related Concepts¶
- [[Java Streams]]
- [[Collectors]]
- [[Functional Programming]]
- [[Aggregate Operations]]
Sources¶
600-developer__java__java8__java8.md