Java – replace switch with binaryoperator
•
Java
I'm trying to replace the common switch for arithmetic operations with the binaryoperator function interface
The basic method is:
private static int computeOne(int res,String operand,String operation) {
int number = Integer.parseInt(operand);
switch (operation) {
case "+":
res += number;
break;
case "-":
res -= number;
break;
case "*":
res *= number;
break;
case "/":
res = (number != 0 ? res / number : Integer.MAX_VALUE);
break;
default:
res = 0;
System.out.println("unkNown operation");
}
return res;
}
As far as I know, it is necessary to write something like this:
BinaryOperator<Integer> action = (a,b) -> computeExpression(a + operation + b); action.apply(res,operand);
But I don't know how to avoid switching the same switch as computeone in computeexpression
Solution
You can define binaryoperator < integer > for each arithmetic operation:
// a = operand 1 // b = operand 2 (a,b) -> a * b; (a,b) -> a + b; (a,b) -> a / b; (a,b) -> a - b;
Then you can apply a pass 2 parameters:
// result = operation.apply(a,b); int result = ((BinaryOperator<Integer>) ((a,b) -> a * b)).apply(2,2);
I will use enumeration to enumerate these operations:
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<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);
}
}
}
You can also use bifunction < < binaryoperator , Pair<?,?>,?> To "simplify" it:
// BiFunction<Operator,Operands,Result>
// Operator = BinaryOperator<?>
// Operands = 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)); // 4
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
