Introduction to Lambda expressions in java



Lambda expression is updated after java8, is used to simplify the implementation of anonymous inner classes of functional interfaces. The so-called functional interface means that the interface has only one abstract method (an interface can also have default methods, private methods, and class methods, but there can only be one abstract method) .

When you need to pass behavior as a parameter to a method, you can write the method parameters as functional interface types, and then use Lambda expressions to create implementation class objects and pass them into the method as actual parameters.

The core purpose of Lambda expressions is to simplify code. The side effect of simplification is that it is not intuitive enough, but if you master the omission method, the code will look very elegant.



Lambda expression syntax

The general syntax format is:
(parameter list) -> {statement in method body}

Because Lambda expressions are used to create implementation class objects of functional interfaces, the type of the interface can be determined by the formal parameters of the called method, so it can be omitted directly.
And the functional interface has only one abstract method, so you only need to rewrite the abstract method . For overridden abstract methods, the method name is fixed and can be confirmed at the interface definition and can be omitted directly. Therefore, you only need to write out the parameter list of the method, and then add the method body part overridden by the implementation class to complete the implementation class definition of the functional interface.
So you can see that the left side of the general syntax is the parameter list part, which corresponds to the effective information of the abstract method method header, and the right side is the execution statement of the method body, which corresponds to the core information of the abstract method method body. So the above syntax format may seem weird, but it is actually a sufficiently simplified result.

Use anonymous inner classes and corresponding Lambda expressions as examples:

@FunctionalInterface
interface InterA {
    
    
    int add(int a, int b);
}

public class LambdaDemo1 {
    
    
    public static void main(String[] args) {
    
    
    	// 这里传入匿名内部类创建的对象
        userInterA(new InterA() {
    
    
            @Override
            public int add(int a, int b) {
    
    
                return a + b;
            }
        });
		// 省略后的对应Lambda表达式,左边是抽象方法的形参列表,右边是重写的方法体
		// 参照上面,可以完全找到对应关系,但下面的代码明显更简洁
        userInterA((int a, int b) -> {
    
    return a + b;});
    }
    
    public static void userInterA(InterA a) {
    
    
        int num = a.add(6, 5);
        System.out.println(num);
    }
}


Lambda expression omission

In order to further simplify, Lambda expressions can be further simplified. The following are the rules for simplification:

  1. The formal parameter type of the formal parameter list can be omitted.
    In fact, it is easy to understand, because the formal parameter type has been fixed in the interface definition part, and there is no need to rewrite it.
  2. If the formal parameter has only one parameter, the parentheses can be omitted.
  3. If the method body has only one line of statements, can omit the curly braces,Note that the semicolon at the end of the statement should also be removed. If the only statement is the return statement , must omit the return keyword , the system will detect that the method needs to return a value, and will directly return the result of the expression as the return value.

Method reference and constructor reference

If the method body of the Lambda expression to be overridden by an abstract method has only one line and meets the following conditions, it can be further abbreviated and divided into the following situations:

1. Reference class method
If the format of the Lambda expression is: (a,b,…) -> class name.class method (a,b,…)< /span>Class name::Class method. In this case, it can be abbreviated as : all parameters in the formal parameter list will be used as corresponding parameters of the reference class method
Note that

  1. Referring to the instance method of a specific object
    If the format of the Lambda expression is: (a,b,…) -> Specific object name.Instance method (a,b,…) )
    Note that all parameters in the formal parameter list will be used as corresponding parameters of the instance method that refers to a specific object. This can be abbreviated as: Specific object name::instance method

  2. References an instance method of an object
    If the format of the Lambda expression is: (a,b,c,…) -> a.Instance method (b,c, …)
    Note that the first parameter in the parameter list is used as the caller, and the remaining parameters are all used as corresponding parameters on the right side , then it can be abbreviated as: Class name::Instance method, where the class name is the type of the first parameter.

  3. Reference constructor
    If the format of the Lambda expression is: (a,b,…) -> new class name (a,b,…)< a i=2> Note that all parameters in the parameter list are used as corresponding parameters of the called constructor. In this case, it can be abbreviated as: < a i=5>Class name::new



Common usage scenarios of Lambda expressions

Divided into three types:

  1. Reference variables assigned to functional interface types
  2. Passed to a method as a parameter of a functional interface type
  3. Casting Lambda Expressions Using Functional Interfaces

The type of Lambda expression is not fixed and depends entirely on which functional interface is implemented, so the implementation class object created by Lambda expression will change according to the usage scenario. .



Lambda expressions and anonymous inner classes

The essence of Lambda expression is the abbreviation of the anonymous inner class corresponding to the functional interface. If the anonymous inner class is to implement the functional interface, it can be replaced by Lambda expression.
But Lambda expressions can only override abstract methods and cannot add new methods.
And although the object created by the Lambda expression can inherit the default method of the interface, The default method in the interface cannot be called in the Lambda expression .

But many things that anonymous inner classes can do, Lambda expressions can also do:

  1. You can directly access "effectively final" local variables, as well as member variables of external classes (including instance variables and class variables, of course, only class variables can be accessed in class methods).
  2. Created objects can directly call the default methods inherited from the interface.


Lambda expressions and annotations

Because Lambda expressions can only be used as implementation class objects of functional interfaces, you can add annotations before the functional interface definition. If the interface is not a functional interface, an error will be reported.
Annotation: @FunctionalInterface



Guess you like

Origin blog.csdn.net/qq_983030560/article/details/131700670