Java中如何将简单foreach循环转换为Stream.reduce或其他非for循环实现?
完全可以实现,你这段迭代逻辑本质是典型的顺序累加归约场景,和Stream.reduce的语义完全匹配,改造后的代码如下:
public class Expression { private final List<Operation> operations; public Expression(List<Operation> operations) { this.operations = operations; } int eval() { return operations.stream() .reduce( 0, // 与原逻辑完全一致的初始计算值 (currentResult, operation) -> operation.execute(currentResult), // 运算存在严格顺序依赖,禁止并行执行避免结果出错 (res1, res2) -> { throw new UnsupportedOperationException("不支持并行计算"); } ); } }
说明
- 实现逻辑和原for循环完全等价:如果
operations是空列表,会直接返回初始值0,和原有行为完全对齐。 - 这里选用三个参数的
reduce重载,是因为流元素类型为Operation,而累加结果类型为int,二者类型不匹配,需要额外指定合并器。 - 由于运算的输入依赖前一步的输出,有严格的顺序要求,因此不要使用并行流,否则会打乱执行顺序得到错误结果。
内容的提问来源于stack exchange,提问作者infinitesimal
相关产品推荐
相关产品推荐

