How to map lambda expressions in Java

I come from Python and try to understand how lambda expressions work in Java In Python, you can do the following:

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)

How to accomplish similar operations in Java? I've read something about Java lambda expressions. It seems that I must declare an interface first, and I don't know how and why you need to do so

Edit: I try to do this myself using a custom interface This is the code I tried:

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);
}

However, this can produce errors:

Where do I declare interfaces?

Solution

Using bifunctions in Java 8 is easy:

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);

The syntax is indeed a bit verbose than python, and it may be better to use getordefault on opdict to avoid using non-existent operators, but this should at least get scrolling

If you only use int, it's better to use intbinaryoperator because it takes care of any generic type you have to do

final Map<String,IntBinaryOperator> opdict = new HashMap<>();
opdict.put("+",y) -> x / y);

int sum = opdict.get("+").applyAsInt(5,4);
System.out.println(sum);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>