java – 用BinaryOperator替换开关

我正在尝试用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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...