Stream Reduce Three Overloads
Fold a stream to one value three ways: with identity, as Optional without identity, and in parallel where the combiner merges partial sums.
Code
import java.util.List;
import java.util.Optional;
public class BasketTotal {
public static void main(String[] args) {
List<Integer> cents = List.of(1250, 499, 3200, 89);
// 形态一:给 identity —— 空流也返回恒等值,结果类型确定
int total = cents.stream().reduce(0, Integer::sum);
System.out.println("total = " + total);
// 形态二:不给 identity —— 返回 Optional,空流得 Optional.empty(),
// 不会用一个编造的默认值冒充真实计算结果
Optional<Integer> max = cents.stream().reduce(Integer::max);
System.out.println("max = " + max);
// 形态三:identity + accumulator + combiner ——
// parallel 流分段累加,combiner 只负责把各段部分和再相加
int parallelTotal = cents.parallelStream().reduce(0, Integer::sum, Integer::sum);
System.out.println("parallel total = " + parallelTotal);
}
}How it works
Stream Reduce Three Overloads keeps everything in the class BasketTotal and the function main.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable. Optional wraps the possibly-absent value instead of a null sentinel.
Putting it to use
The demo output is labeled (total =, max =, parallel total =), so every printed line maps back to its originating operation.
Core lines
Optional<Integer> max = cents.stream().reduce(Integer::max);
int total = cents.stream().reduce(0, Integer::sum);
int parallelTotal = cents.parallelStream().reduce(0, Integer::sum, Integer::sum);
Interactive Tools for This Topic
FAQ
- What does Stream Reduce Three Overloads print when run?
- Running the file directly is enough — expect labeled output lines such as `total =`, `max =`, `parallel total =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.