用BinaryOperator替换开关

时间:2018-04-06 19:26:22

标签: java java-8 functional-interface binary-operators

我试图通过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);

但我不明白如何避免switch中与computeExpression相同的computeOne

2 个答案:

答案 0 :(得分:8)

您可以为每个算术运算定义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, "2", "*"));  // 8
         System.out.println(computeOne(4, "2", "-"));  // 2
         System.out.println(computeOne(4, "2", "+"));  // 6
    }

    private static int computeOne(int res, String operand, String operation) {
        return Operation.getOperationBySymbol(operation)
                        .getBinaryOperator()
                        .apply(res, Integer.parseInt(operand));
    }

    private enum Operation {
        // operation = symbol, action
        MULTIPLICATION("*", (a, b) -> a * b),
        ADDITION("+", (a, b) -> a + b),
        SUBTRACTION("-", (a, b) -> a - b),
        DIVISION("/", (a, 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);
        }
    }

}

你也可以简化&#34;它带有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

答案 1 :(得分:3)

算术运算符不能是变量 通过使用功能接口或不使用实际代码,您将具有相同的约束:将String运算符转换为算术运算符。

此外,实际上在computeOne()您接受了int和两个String作为参数,并返回int
BinaryOperator<Integer>接受两个Integer并返回Integer 所以它不兼容。
您需要TriFunction,但它不存在 创建自己的功能界面,例如TriFunction<T,U,V,R> 或减少传递给函数的参数数量。

以下示例使用枚举OperatorBiFunction结合使用,与您的实际方法执行相同的操作。
请注意,由于运算符现在由负责执行函数的枚举Operator表示,因此该函数现在只需要两个参数:IntegerString,您将其转换为{{ 1}}。
所以int没问题。

BiFunction<Integer, String, Integer>

您可以创建如下操作:

public enum Operator{
    ADD("+", (a,b) -> a + Integer.parseInt(b)), 
    SUBSTRACT("-", (a,b) -> a - Integer.parseInt(b)),
    MULTIPLY("*", (a,b) -> a * Integer.parseInt(b)),
    //       ...
    DEFAULT("", (a,b) -> 0);

    public BiFunction<Integer, String, Integer> function;
    private String symbol;

    Operator(String symbol, BiFunction<Integer, String, Integer> function){
        this.symbol = symbol;
        this.function = function;
    }

    public int compute(int actualValue, String operand){
        return function.apply(actualValue, operand);
    }

    public static Operator of(String symbol) {
        for (Operator value : values()) {
            if (symbol.equals(value.symbol)) {
                return value;
            }
        }

        return Operator.DEFAULT;
    }

}