lambda expression

Syntax of lambda expressions

(type1 arg1, type2 arg2, ...) -> { /*代码块*/ }

However, there are various abbreviations in each case:

  1. The parameter type can be omitted, the system will judge the parameter type according to the context, like this(arg1,arg2, ...) -> { /*代码块*/ }
  2. When there is only one parameter, () can also be omitted, like thisarg -> { /*代码块*/ }
  3. When there is only one statement, {} can be omitted, like thisarg -> System.out.println(arg)
  4. When there are no parameters, () needs to be written, like this() -> { /*代码块*/ }

where lambda is used

The target type of lambda (or simply, the type of lambda) is a functional interface (the so-called functional interface is an interface that contains only one abstract method), so lambda expressions may be used in the following situations:
1 .As a parameter of a functional interface type to a method, like this new Thread(() -> { /*代码块*/ }).start();
2. Assign to a variable of a functional interface type, like this Runnable r = () -> { /*代码块*/ };
3. Use a functional interface to cast the lambda expression, like thisObject obj = (Runnable) () -> { /*代码块*/ };

The connection between lambda and anonymous inner class

1. lambda expressions can access local variables (finally modified) like anonymous inner classes, as well as member variables of outer classes.
2. lambda expressions, like anonymous inner classes, create objects that can call the default methods of the interface.

Difference between lambda and anonymous inner class

1. Lambda expressions can only create instances for functional interfaces (that is, interfaces with only one abstract method), while anonymous functions have no restrictions.
2. The default method of the interface can be called in the abstract method body implemented by the anonymous class, but the default method of the interface cannot be called in the code block of the lambda.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325164857&siteId=291194637
Recommended