将简单的 foreach 循环转换为流

Converting simple foreach loop to stream

假设我有一个简单的 class 方法 eval()。除了使用 for 循环外,是否可以将此方法转换为 stream.reduce 或类似的方法? Operation 是方法 execute 的许多可能实现的接口,这些实现计算不同的算术运算。

public class Expression {
    private final List<Operation> operations;

    public Expression(List<Operation> operations) {
        this.operations = operations;
    }

    int eval() {
        int result = 0;
        for (Operation operation: operations) {
            result = operation.execute(result);
        }
        return result;
    }
}

forEach

为什么不尝试将 forEach() 作为最简单和最常见的操作;它遍历流元素,在每个元素上调用提供的函数。

public void eval() {    
    operations.stream().forEach(e -> e.execute());
         
}

这将有效地调用操作中每个元素的 execute()。

此外,请注意您当前的代码,result 将执行操作的最新结果,但不是全部。

试试这个。

int eval() {
    int[] r = {0};
    operations.stream()
        .forEach(op -> r[0] = op.execute(r[0]));
    return r[0];
}