实现说明
Stream reduce 三种重载可以归结为类 BasketTotal和函数 main。
管道就是一个 stream:数据源、惰性中间步骤、一个终端收集器。缺席用 Optional 建模——类型系统会提醒你先检查再拆包。
使用要点
- 跑完文件,输出里会留下标记——
total =、max =、parallel total =。
常见问题
运行「Stream reduce 三种重载」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 total =、max =、parallel total = 标签标明各步骤。
核心语句
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);
代码示例
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);
}
}