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;