您可以使用 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
注意,我正在使用Java 10,如果您没有使用Java 9 +,则可以像这样添加到您的地图中:Map.of("+", add, "-", sub);
Map<String, BinaryOperator<Integer>> signs = new HashMap<>();
signs.put("+", add);
signs.put("-", sub);
Ideone demo
良好做法
正如@Boris蜘蛛和@Holger在注释中已经说过的那样,最好使用它来避免装箱,最后你的代码可以看起来像这样: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)));