New features of jdk1.8 Lambda expression

Lambda expression

definition:

Lambda expressions can also be called "closures", which is one of the new features released by jdk1.8, allowing functions to be passed as parameters of a method.

The syntax format of lambda expression:

(Parameter list) ->{ code}


(Parameter list): Represents the parameter list of the abstract method in the interface
->: The meaning of passing, the parameters in the parentheses are passed to the method weight
{}: Inside is the specific code to rewrite the abstract method in the interface
Syntax shorthand for lambda expression
1. Parameters:

On the basis of the standard format, the data type of the parameter list can be omitted.
On the basis of the standard format, when there is only one parameter in the parentheses, the data type of the parameter and the parentheses can be omitted.

2. Code:

On the basis of the standard format, when there is only one line of code in braces,
braces {}, the return keyword, and the semicolon at the end of the code;
all can be omitted but must be omitted or exist at the same time

The premise of lambda expression

1. There must be an interface, and there is only one abstract method in the interface
2. The parameter type of the method must be the interface type corresponding to the lambda expression

Use scenarios of lambda expressions

Simplify anonymous inner classes

//使用匿名内部类创建线程
       new Thread(
               new Runnable()
               {
    
    
                   @Override
                   public void run()
                   {
    
    
                       System.out.println("线程执行的任务");
                   }
               }
       ).start();
//使用Lambda表达式创建线程
       new Thread(
               () ->{
    
    
                   System.out.println("线程执行的任务");
               }
       ).start();
other

An interface with only one abstract method is called a functional interface

Guess you like

Origin blog.csdn.net/weixin_45864391/article/details/108201449