binaryoperator java_java – 用BinaryOperator替换开关

您可以定义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) ((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 binaryOperator;

private final String symbol;

Operation(String symbol,BinaryOperator binaryOperator) {

this.symbol = symbol;

this.binaryOperator = binaryOperator;

}

public BinaryOperator 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 = BinaryOperator>

// Operands = Pair,?>

BiFunction,Pair,Integer> f =

(operator,operands) ->

operator.apply(operands.getKey(),operands.getValue());

f.apply((a,b) -> a + b,new Pair<>(2,2)); // 4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值