b_p*_*kes 6 python java lambda
我来自Python,并试图了解lambda表达式在Java中的工作方式.在Python中,您可以执行以下操作:
opdict = { "+":lambda a,b: a+b, "-": lambda a,b: a-b,
"*": lambda a,b: a*b, "/": lambda a,b: a/b }
sum = opdict["+"](5,4)
Run Code Online (Sandbox Code Playgroud)
如何在Java中完成类似的操作?我已经阅读了一些关于Java lambda表达式的内容,似乎我必须首先声明一个接口,而且我不清楚你需要如何以及为什么要这样做.
编辑:我尝试使用自定义界面自己完成此操作.这是我尝试过的代码:
Map<String, MathOperation> opMap = new HashMap<String, MathOperation>(){
{ put("+",(a,b)->b+a);
put("-",(a,b)->b-a);
put("*",(a,b)->b*a);
put("/",(a,b)->b/a); }
};
...
...
interface MathOperation {
double operation(double a, double b);
}
Run Code Online (Sandbox Code Playgroud)
但是,这会产生错误:
此表达式的目标类型必须是功能接口.
我在哪里声明接口?
使用BiFunctionJava 8 很容易:
final Map<String, BiFunction<Integer, Integer, Integer>> opdict = new HashMap<>();
opdict.put("+", (x, y) -> x + y);
opdict.put("-", (x, y) -> x - y);
opdict.put("*", (x, y) -> x * y);
opdict.put("/", (x, y) -> x / y);
int sum = opdict.get("+").apply(5, 4);
System.out.println(sum);
Run Code Online (Sandbox Code Playgroud)
语法比Python确实要冗长一些,并且使用getOrDefaulton opdict可能更好,以避免使用不存在的运算符的情况,但这应该至少得到滚动.
如果你只使用ints,IntBinaryOperator最好使用,因为这会照顾你必须做的任何通用类型.
final Map<String, IntBinaryOperator> opdict = new HashMap<>();
opdict.put("+", (x, y) -> x + y);
opdict.put("-", (x, y) -> x - y);
opdict.put("*", (x, y) -> x * y);
opdict.put("/", (x, y) -> x / y);
int sum = opdict.get("+").applyAsInt(5, 4);
System.out.println(sum);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
234 次 |
| 最近记录: |