小编Rom*_*rov的帖子

用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;
}
Run Code Online (Sandbox Code Playgroud)

据我所知,编写类似的内容是必要的:

BinaryOperator<Integer> action = (a,b) -> computeExpression(a + operation + b);
action.apply(res, operand);
Run Code Online (Sandbox Code Playgroud)

但我不明白如何避免switchcomputeExpression …

java binary-operators java-8 functional-interface

8
推荐指数
1
解决办法
146
查看次数