您可以定义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个参数:
// result = operation.apply(a,b);
int result = ((BinaryOperator) ((a,b) -> a * b)).apply(2,2);
我会使用枚举来枚举这些操作:
class Test {
public static void main(String[] args) {
System.out.println(computeOne(4,"2","/")); // 2
System.out.println(computeOne(4,"*")); // 8
System.out.println(computeOne(4,"-")); // 2
System.out.println(computeOne(4,"+")); // 6
}
private static int computeOne(int res,String operation) {
return Operation.getOperationBySymbol(operation)
.getBinaryOperator()
.apply(res,Integer.parseInt(operand));
}
private enum Operation {
// operation = symbol,action
MULTIPLICATION("*",(a,b) -> a * b),ADDITION("+",b) -> a + b),SUBTRACTION("-",b) -> a - b),DIVISION("/",b) -> a / b);
private final BinaryOperator binaryOperator;
private final String symbol;
Operation(String symbol,BinaryOperator binaryOperator) {
this.symbol = symbol;
this.binaryOperator = binaryOperator;
}
public BinaryOperator 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
// Operator = BinaryOperator>
// Operands = Pair,?>
BiFunction,Pair,Integer> f =
(operator,operands) ->
operator.apply(operands.getKey(),operands.getValue());
f.apply((a,b) -> a + b,new Pair<>(2,2)); // 4