java 8动态链接时可以使用累加器吗

java 8动态链接时可以使用累加器吗,java,java-8,java-stream,Java,Java 8,Java Stream,在java 8中开发时,我们开始尝试实现最大不变性,最后我们来到了这个角落: rover = rover.move(new Commands("RFF"); 我们认为可以在这里练习Streams语法,但我们无法理解: return commands.foreach((this, rover, command) -> rover = rover.move(command)).getAccumulator(); “this”作为种子,rover作为累加器,command作为阵列中的每个命

在java 8中开发时,我们开始尝试实现最大不变性,最后我们来到了这个角落:

rover = rover.move(new Commands("RFF");

我们认为可以在这里练习Streams语法,但我们无法理解:

return commands.foreach((this, rover, command) -> rover = rover.move(command)).getAccumulator();

“this”作为种子,rover作为累加器,command作为阵列中的每个命令。我以为我在一次函数式编程培训中用C#做过这种事情。但不确定:)

您要找的操作员是。你可以这样使用它:

return commands.reduce(this,Rover::move,(r1,r2)->{throw new UnsupportedOperationException();});

不幸的是
reduce
要求您处理值的组合,而这是您的系统无法做到的。因此,在这种情况下,您必须抛出一个异常。我认为您当前的循环解决方案很好,正如其他评论所说,不建议“仅仅因为”而切换到流。

对于那些感兴趣的人:我们当前的最佳努力导致了以下结果:

class Rover {

    public Rover move(Commands commands) {
        BiFunction<Rover, ? super Command, Rover> action = Rover::move;
        return commands.executeAccumulativelyStartingWith(this, action);
    }

    public Rover move(Command command){
        return command.executeOn(this);
    }
    ...
}

class Commands {

    public Rover executeAccumulativelyStartingWith(Rover initialRover, BiFunction<Rover, ? super Command, Rover> action) {
        BinaryOperator<Rover> combiner = (r1, r2) -> {throw new UnsupportedOperationException();};
        return commands.stream().reduce(initialRover, action, combiner);
    }
    ...
}
classrover{
公共漫游者移动(命令){
双功能动作=漫游者::移动;
return commands.ExecuteAcumulativelyStartingWith(此操作);
}
公共漫游者移动(命令){
return命令.executeOn(this);
}
...
}
类命令{
public Rover ExecuteAccumativeElystatingWith(漫游者初始漫游者,双功能操作){
BinaryOperator组合器=(r1,r2)->{抛出新的UnsupportedOperationException();};
return commands.stream().reduce(initialRover、action、combiner);
}
...
}

您似乎在寻找的内容非常类似于用于收集输出的自定义
收集器。它很可能由
reduce
实现,但这取决于
命令.asArray
rover.move
的定义。另外,您是否打算使用不同的类
Command
Commands
?没有“流的力量”可以证明将示例中简单、直接的循环更改为更复杂的循环是合理的。如果您想改进代码,请使
命令
实现
可编辑
,以避免每次迭代都需要将内容复制到数组中。本例的功能在于“探索”它们在kata过程中的工作方式。所以我们可以理解它们的语法和用法。这种能力还在于学会思考更多的功能,并减少代码中赋值的数量(易变性)。@Naman:你说得对!我们立即更新了代码。它工作得很好-但我不知道它有多完整:Rover::Move是对要合并应用的函数的引用(r2=r1.Move(c[0]),然后(r2=r2.Move(c[1]))'在流的最后返回最后一个r2的值,但是合并器会做什么,为什么它需要抛出异常。。。
class Rover {

    public Rover move(Commands commands) {
        BiFunction<Rover, ? super Command, Rover> action = Rover::move;
        return commands.executeAccumulativelyStartingWith(this, action);
    }

    public Rover move(Command command){
        return command.executeOn(this);
    }
    ...
}

class Commands {

    public Rover executeAccumulativelyStartingWith(Rover initialRover, BiFunction<Rover, ? super Command, Rover> action) {
        BinaryOperator<Rover> combiner = (r1, r2) -> {throw new UnsupportedOperationException();};
        return commands.stream().reduce(initialRover, action, combiner);
    }
    ...
}