java – 用BinaryOperator替换开关
发布时间:2020-05-28 14:22:57 所属栏目:Java 来源:互联网
导读:我正在尝试用BinaryOperator功能接口替换用于算术运算的公共开关. 基本方法是: private static int computeOne(int res, String operand, String operation) { int number = Integer.parseInt(operand); switch (operation) { c
|
我正在尝试用BinaryOperator功能接口替换用于算术运算的公共开关. 基本方法是: 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;
}
据我所知,写下这样的东西是必要的: BinaryOperator<Integer> action = (a,b) -> computeExpression(a + operation + b); action.apply(res,operand); 但我不明白如何避免在computeExpression中切换与computeOne相同的切换. 解决方法您可以定义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<Integer>) ((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<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<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 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
