I am coming from Python and trying to understand how lambda expressions work differently in Java. In Python, you can do things like:
opdict = { "+":lambda a,b: a+b, "-": lambda a,b: ab, "*": lambda a,b: a*b, "/": lambda a,b: a/b } sum = opdict["+"](5,4)
How can I do something like this in Java? I read a little about Java iambda expressions, and it seems to me that I should declare the interface first, and I donβt understand how and why you need to do this.
Edit: I tried to do this myself using a special interface. Here is the code I tried:
Map<String, MathOperation> opMap = new HashMap<String, MathOperation>(){ { put("+",(a,b)->b+a); put("-",(a,b)->ba); put("*",(a,b)->b*a); put("/",(a,b)->b/a); } }; ... ... interface MathOperation { double operation(double a, double b); }
However, this gives an error:
The target type of this expression must be a functional interface.
Where exactly do I declare the interface?