如何用BinaryOperator函数式接口替换算术运算中的switch语句
Refactoring Arithmetic Switch to BinaryOperator
Let's ditch that clunky switch statement and use Java's BinaryOperator<Integer> to make your arithmetic computation code more concise and maintainable. Here's a step-by-step breakdown:
1. Create a Mapping of Operations to BinaryOperator
First, we'll define an immutable map that maps each operation string to a corresponding BinaryOperator<Integer> implementation. This replaces the switch cases with a clean lookup table:
private static final Map<String, BinaryOperator<Integer>> OPERATION_MAP = Map.of( "+", Integer::sum, "-", (a, b) -> a - b, "*", (a, b) -> a * b, "/", (a, b) -> b != 0 ? a / b : Integer.MAX_VALUE );
Integer::sumis a neat method reference for addition, equivalent to writing(a,b) -> a + b.- For subtraction, multiplication, and division, we use lambda expressions to define the logic directly. The division case retains your existing zero-check to avoid throwing an
ArithmeticException.
2. Refactor the computeOne Method
Now we can rewrite your method to use this map instead of the switch statement:
private static int computeOne(int res, String operand, String operation) { int number = Integer.parseInt(operand); // Fetch the operator from our map, or use a default handler if it's unknown BinaryOperator<Integer> operator = OPERATION_MAP.getOrDefault(operation, (a, b) -> { System.out.println("unknown operation"); return 0; }); // Execute the operation and return the result return operator.apply(res, number); }
How This Works
OPERATION_MAP.getOrDefault()handles both valid and invalid operations: if the operation exists in the map, we get the correspondingBinaryOperator; if not, we fall back to the default lambda that prints an error and returns 0 (matching your original default case).- The
apply()method ofBinaryOperatortakes your current result and the parsed number, then runs the arithmetic logic we defined.
Bonus: Scalability Win
If you need to add more operations later (like modulo %), you just add a new entry to the OPERATION_MAP—no need to modify a long switch statement. This makes the code way easier to maintain!
内容的提问来源于stack exchange,提问作者Roman Vinokurov
相关产品推荐
相关产品推荐

