如何在Java中映射lambda表达式

时间:2015-10-11 22:16:06

标签: java python 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) 

如何在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);
}

然而,这会产生错误:

  

此表达式的目标类型必须是功能接口。

我在哪里声明接口?

2 个答案:

答案 0 :(得分:8)

在Java 8中使用BiFunction很容易:

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

确保语法比Python更冗长,并且在getOrDefault上使用opdict可能更好,以避免使用不使用运算符的情况存在,但至少应该让球滚动。

如果您完全使用int,则最好使用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);

答案 1 :(得分:2)

另一种解决方案是使用枚举:

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

然后你可以这样做:

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

这并不像其他解决方案那样简洁,但使用枚举而不是String意味着当您在IDE中键入Operation.时,您将看到所有可能操作的列表。