background

Lambda expressions were a big reason for the release of Java8, which began by allowing methods to be passed as arguments as variables, and using such expressions made Java code much cleaner.

Syntax format
(params) -> expression
(params) -> {expression} 

{} is not used if the expression expression has only one sentence in it. Alternatively, the expression expression has no arguments.

() -> {expression} 或是 () -> expression 
The sample
  • The expression is evaluated using (params) -> expression
public static void main(String[] args) {
    
    Method method1 = (int a,int b) -> a + b;
    int res1 = method1.math(2, 3);
    System.out.println(res1);
    Method method2 = (int a,int b) -> a * b;
    int res2 = method2.math(2, 3);
    System.out.println(res2);
  }
  
  public interface Method{
    public int math(int a,int b);
  } 

If there is no {} expression, it must have only one expression. Otherwise, an error will be reported.

  • Use (params) -> {expression} to evaluate the expression
public static void main(String[] args) {
    
    Method method1 = (int a,int b) -> { return (a + b); };
    int res1 = method1.math(2, 3);
    System.out.println(res1);
    Method method2 = (int a,int b) -> {return (a * b); };
    int res2 = method2.math(2, 3);
    System.out.println(res2);
    
  }
  
  public interface Method{
    public int math(int a,int b);
  } 

When using this expression, you must specify exactly what is returned. For example, return (a + b), return (a * b) are all explicit.

Note: After the Lambda expression is executed, the total return must be an interface, such as the Method interface above.

Variable scope

An important point to make when using Lambda expressions is the scope of variables. If the expression needs to refer to an external variable for operation, the final keyword must be added. If the final keyword is not added, the value of this variable cannot be changed in the backward coding. For example, as follows:

public static void main(String[] args) {
    final int c = 3;
    Method method1 = (int a,int b) -> { return (a + b + c); };
    int res1 = method1.math(2, 3);
    System.out.println(res1);
  }
  
  public interface Method{
    public int math(int a,int b);
  } 

When we reference the variable c to an expression, we append the final keyword to the variable c so that it cannot be changed.

public static void main(String[] args) {
    int c = 3;
    Method method1 = (int a,int b) -> { return (a + b + c); };
    int res1 = method1.math(2, 3);
    System.out.println(res1);
    c = 10;
  }
  
  public interface Method{
    public int math(int a,int b);
  } 

Referencing the variable c to an expression and assigning the value of 10 to the variable c in subsequent executions will result in an error when Lambda expressions are used.

Looking forward to

Welcome to “Lao Wang said programming”, every day a little progress, your every thumb up, in the view, share is committed to reduce the “Siege Lion” output bugs.