你总是在减法操作符
-
上执行正向求和
+=
。但是考虑使用
Stream
-API如何呢?
IntStream.of(1, 2, 3, 4, 5)
.reduce(operatorFunction('-'))
.ifPresent(System.out::println);
使用以下IntBinaryOperator
返回函数:
static IntBinaryOperator operatorFunction(char operator) {
if (operator == '-') {
return (int1, int2) -> int1 - int2;
}
return (int1, int2) -> int1 + int2;
}
这将按预期打印-13
。这就是你所需要的。请注意,您还可以使用IntStream.sum
来实现简单的求和。但是,使用operatorFunction
,如果您希望稍后添加*
或÷
,也可以进行加法。
另一种编写上述代码的方法(带有中间值):
int[] yourInputArray = {1, 2, 3, 4, 5};
char operator = '-';
OptionalInt = Stream.of(yourInputArray)
.reduce(operatorFunction(operator));
从这里你可以调用 orElse(0)
或者使用 orElseThrow(() -> ...)
抛出异常等。查看 OptionalInt
-javadoc 以获取更多选项。一旦你离开原始的 int
,你可能想通过使用 Stream
, BinaryOperator<Integer>
和 Optional<Integer>
来交换代码。
顺便说一下,你当前的代码中也有一个 IndexOutOfBoundException
。但是为什么要搞索引和数组呢?如果你可以使用 Stream
和如此少的代码行呢?