在这种情况下,您可以像这样使用BinaryOperator<Integer>:
BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + b
BinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b
// Then create a new Map which take the sign and the corresponding BinaryOperator
// equivalent to signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}
Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub);
int a = 5; // a = 5
int b = 3; // b = 3
// Loop over the sings map and apply the operation
signs.values().forEach(v -> System.out.println(v.apply(a, b)));
输出
8
2
注意Map.of("+", add, "-", sub); 我使用的是 Java 10,如果你没有使用 Java 9+,你可以像这样添加到你的地图中:
Map<String, BinaryOperator<Integer>> signs = new HashMap<>();
signs.put("+", add);
signs.put("-", sub);
Ideone demo
良好做法
正如@Boris the Spider 和@Holger 在cmets 中已经说过的,最好使用IntBinaryOperator 来避免装箱,最终您的代码可以如下所示:
// signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}
Map<String, IntBinaryOperator> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);
int a = 5; // a = 5
int b = 3; // b = 3
// for i in signs.keys(): print(signs[i](a,b))
signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));