Lambda 风格的传统风格

传统方式

interface MathOperation{
    boolean unaryOperation(int num);
}

public class LambdaTry {
    public static void main(String[] args) {
        MathOperation isEven = new MathOperation() {
            @Override
            public boolean unaryOperation(int num) {
                return num%2 == 0;
            }
        };
        
        System.out.println(isEven.unaryOperation(25));
        System.out.println(isEven.unaryOperation(20));
    }
}

Lambda 风格

  1. 删除类名和功能接口体。
public class LambdaTry {
    public static void main(String[] args) {
        MathOperation isEven = (int num) -> {
            return num%2 == 0;
        };
        
        System.out.println(isEven.unaryOperation(25));
        System.out.println(isEven.unaryOperation(20));
    }
}
  1. 可选的类型声明
MathOperation isEven = (num) -> {
    return num%2 == 0;
};
  1. 参数的可选括号,如果是单个参数
MathOperation isEven = num -> {
    return num%2 == 0;
};
  1. 如果函数体中只有一行,则可选花括号
  2. 如果函数体中只有一行,则可选返回关键字
MathOperation isEven = num -> num%2 == 0;