How to display lambda expressions in Java

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?

+6
source share
2 answers

Easy enough to make BiFunction in Java 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); 

The syntax is a bit more verbose than Python, and using getOrDefault on opdict probably be preferable to avoid a scenario in which you use an operator that does not exist, but this should be at least a ball roll.

If you work exclusively with int s, it is preferable to use IntBinaryOperator , as this will take care of any typical type that you will need to do.

 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); 
+8
source

An alternative solution is to use an enumeration:

 public enum Operation { PLUS((x, y) -> x + y), MINUS((x, y) -> x - y), TIMES((x, y) -> x * y), DIVIDE((x, y) -> x / y); private final IntBinaryOperator op; Operation(IntBinaryOperator op) { this.op = op; } public int apply(int x, int y) { return op.applyAsInt(x, y); } } 

Then you can do:

 int sum = Operation.PLUS.apply(5, 4); 

It is not as simple as other solutions, but using an enumeration rather than String means that when you type Operation. in the IDE you will be presented with a list of all possible operations.

+2
source

All Articles