你可以为每个算术操作定义一个
BinaryOperator<Integer>
:
// a = operand 1
// b = operand 2
(a, b) -> a * b;
(a, b) -> a + b;
(a, b) -> a / b;
(a, b) -> a - b;
然后您可以应用一个传递2个参数的操作:
int result = ((BinaryOperator<Integer>) ((a, b) -> a * b)).apply(2, 2);
我会使用一个枚举来列举这些操作:
class Test {
public static void main(String[] args) {
System.out.println(computeOne(4, "2", "/"));
System.out.println(computeOne(4, "2", "*"));
System.out.println(computeOne(4, "2", "-"));
System.out.println(computeOne(4, "2", "+"));
}
private static int computeOne(int res, String operand, String operation) {
return Operation.getOperationBySymbol(operation)
.getBinaryOperator()
.apply(res, Integer.parseInt(operand));
}
private enum Operation {
MULTIPLICATION("*", (a, b) -> a * b),
ADDITION("+", (a, b) -> a + b),
SUBTRACTION("-", (a, b) -> a - b),
DIVISION("/", (a, b) -> a / b);
private final BinaryOperator<Integer> binaryOperator;
private final String symbol;
Operation(String symbol, BinaryOperator<Integer> binaryOperator) {
this.symbol = symbol;
this.binaryOperator = binaryOperator;
}
public BinaryOperator<Integer> getBinaryOperator() {
return binaryOperator;
}
public String getSymbol() {
return symbol;
}
public static Operation getOperationBySymbol(String symbol) {
for (Operation operation : values()) {
if (operation.getSymbol().equals(symbol)) {
return operation;
}
}
throw new IllegalArgumentException("Unknown symbol: " + symbol);
}
}
}
您还可以使用
BiFunction<BinaryOperator<?>, Pair<?, ?>, ?>
来“简化”它:
BiFunction<BinaryOperator<Integer>, Pair<Integer, Integer>, Integer> f =
(operator, operands) ->
operator.apply(operands.getKey(), operands.getValue());
f.apply((a, b) -> a + b, new Pair<>(2, 2));
a + operation + b
看起来会得到“42*14”。为什么要合并它们,当你后来需要拆分它们时? - user unknowncomputeExpression(a, operation, b)
的签名与computeOne
相似。 - Andrew Tobilko