Java Language Traditional style to Lambda style


Example

Traditional way

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 style

  1. Remove class name and functional interface body.
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. Optional type declaration
MathOperation isEven = (num) -> {
    return num%2 == 0;
};
  1. Optional parenthesis around parameter, if it is single parameter
MathOperation isEven = num -> {
    return num%2 == 0;
};
  1. Optional curly braces, if there is only one line in function body
  2. Optional return keyword, if there is only one line in function body
MathOperation isEven = num -> num%2 == 0;