Java 8 lambda表达式的问题

时间:2014-03-20 09:19:25

标签: java lambda java-8

我有一个interface操作a:

interface Operation {
    public double calc(double a, double b);
}

我在enum中使用它。

public enum Operations {

    POWER("^", new Operation(){
        public double calc(double a, double b) {
            return Math.pow(a, b);
        }
    }),
    MULTIPLICATION("*", new Operation(){
        public double calc(double a, double b) {
            return a * b;
        }
    }),
    //...

    private String op;
    private Operation calc;

    public Operations(String op, Operation calc) {
        this.op = op;
        this.calc = calc;
    }
}

我想使用lambda表达式缩短我的代码,但我似乎无法正确使用语法。 oracle教程对我来说有点太复杂了。有人可以用简单的方式向我解释一下吗?

编辑: 我试过了:

POWER ("^", (double a, double b) -> Math.pow(a,b)),等等,但它没有编译。


固定

import java.util.function.*;
public enum Operations {
    POWER("^", Math::pow),
    MULTIPLICATION("*", (double a,double b)->a*b),
    private final String op;
    private final DoubleBinaryOperator calc;
    Operations(String op, DoubleBinaryOperator calc) {
        this.op = op;
        this.calc = calc;
    }
    DoubleBinaryOperator getCalc() {
        return calc;
    }
}

3 个答案:

答案 0 :(得分:8)

Operation是一个功能界面,表达式为:

new Operation(){
    public double calc(double a, double b) {
        return Math.pow(a, b);
    }
}

可以替换为以下lambda表达式:

(a, b) -> Math.pow(a, b)  

或方法参考:

Math::pow

这样,您的enum将成为:

public enum Operations {

    POWER("^", Math::pow),
    MULTIPLICATION("*", (a, b) -> a * b);

    private String op;
    private Operation calc;

    public Operations(String op, Operation calc) {
        this.op = op;
        this.calc = calc;
    }
}

答案 1 :(得分:3)

删除interface Operation,因为这只是DoubleBinaryOperator

public enum Operations {

    POWER("^", Math::pow),
    MULTIPLICATION("*", (a, b) -> a * b);

    private String op;
    private DoubleBinaryOperator calc;

    Operations(String op, DoubleBinaryOperator calc) {
        this.op = op;
        this.calc = calc;
    }
}

您可以Math.pow使用{{1}},因为这已经遵循了所需的签名。

答案 2 :(得分:0)

(a,b)-> Math.pow(a,b)

Math.pow返回一个双精度类型值。如果lambda接受int类型,则将其强制转换为

(a,b)->(int)Math.pow(a,b);