Introduction to lambda in java

lambda

The standard format of lambda expression :
consists of three parts

  • 1. Some parameters
  • 2. An arrow
  • 3. A piece of code

Format :
(parameter list -> {some rewritten method codes};
explanation format
(): the parameter list of the abstract method in the interface. If there is no parameter, leave it blank; if there are parameters, write the parameters, and use commas for multiple parameters Separation
->: the meaning of passing, passing parameters to the method body {}
{}:; the method body of the abstract method rewriting the interface
Note:

  • Lambda must have an interface, and there is only one abstract method in the interface
  • Regardless of jdk built-in runnable, comparator interface or custom interface, lambda can be used only when the abstract method of the interface exists and is unique.
  • 2. It is inferred that lambda must have context.
    That is, the parameter or local variable type in the method must be the interface type corresponding to the lambda, in order to use the lambda as the real column of the interface
    (the content can be deduced from the context, you can omit) the content that the lambda can omit:
    (Parameter list: ) The type of the parameter list in parentheses can be omitted
    (parameter list): if there is only one parameter in the parentheses, the type and () can be omitted
    (some codes) if there is only one line, regardless of whether there is a return value, you can Omit ({}, return,;) Note, omit it together

Code introduction (take thread creation as an example)

public class Demo02lambda {
public static void main(String[] args) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "创建新线程");
        }
    }).start();
    //使用lambda
    new Thread(()-> {
            System.out.println(Thread.currentThread().getName() + "创建1新线程");
        }
   ).start();
    //优化lambda
    //没有参数()不可以省略,只有一行代码,{},;,return可以省
    new Thread(()->System.out.println(Thread.currentThread().getName() + "创建1新线程")
    ).start();
}
}

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/102787601
Recommended