我来自
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)
如何在Java中完成类似的操作?我已经阅读了一些关于Java lambda表达式的内容,似乎我必须首先声明一个接口,而且我不清楚你需要如何以及为什么要这样做.
编辑:我尝试使用自定义界面自己完成此操作.这是我尝试过的代码:
- Map<String,MathOperation> opMap = new HashMap<String,MathOperation>(){
- { put("+",(a,b)->b+a);
- put("-",b)->b-a);
- put("*",b)->b*a);
- put("/",b)->b/a); }
- };
- ...
- ...
- interface MathOperation {
- double operation(double a,double b);
- }
但是,这会产生错误:
The target type of this expression must be a functional interface.
我在哪里声明接口?
解决方法
使用Java 8中的
BiFunction
很容易:
- final Map<String,BiFunction<Integer,Integer,Integer>> opdict = new HashMap<>();
- opdict.put("+",(x,y) -> x + y);
- opdict.put("-",y) -> x - y);
- opdict.put("*",y) -> x * y);
- opdict.put("/",y) -> x / y);
- int sum = opdict.get("+").apply(5,4);
- System.out.println(sum);
语法比Python确实有点冗长,并且在opdict上使用getOrDefault可能更好,以避免使用不存在的运算符的情况,但这应该至少得到滚动.
如果你只使用int,那么使用IntBinaryOperator会更好,因为这会照顾你必须做的任何通用类型.
- final Map<String,IntBinaryOperator> opdict = new HashMap<>();
- opdict.put("+",y) -> x / y);
- int sum = opdict.get("+").applyAsInt(5,4);
- System.out.println(sum);