Detailed explanation of JAVA Lambda expression

Detailed explanation of JAVA Lambda expression

1. Introduction of Lambda expression

1. What is Lambda?

Lambda expressions are a new feature of JDK8 that can replace most anonymous internal classes and write more elegant Java code, especially when traversing collections and other collection operations, which can greatly optimize the code structure.
In the Java language, you can assign a value to a variable.

Can you assign a code block to a variable?

Before Java 8, this was impossible. But after Java 8 came out, you could do it with Lambda features
Here we are.

We can even make grammar more concise.

In this way, we have successfully and elegantly assigned a variable to a "block of code". This code, or the function assigned to a variable, is a Lambda expression. But there's still a question here, what type of variable aBlockOfCode should be?
In Java 8, all Lambda types are an interface, and the Lambda expression itself, that is, the piece of code, needs to be an implementation of that interface. This is one of the keys I think is to understand Lambda, in short
That is, the Lambda expression itself is an implementation of an interface. It might still be a little confusing to say that directly, we
Keep looking at examples. Let's add a type to the aBlockOfCode above:

This type of interface has only one interface function to be implemented. We call it a Functional Interface. To avoid adding interface functions to this interface so that more than one of its interface functions needs to be implemented and become a non-functional interface, we can add a declaration @FunctionalInterface to it so that no one else can add new interface functions to it.

2. What is the use of Lambda?

The most intuitive function is to make the code extremely concise.

3. Interface requirements

Although Lambda expressions can be used to implement some interfaces simply, not all interfaces can be implemented using Lambda expressions. Lambda specifies that there can only be one method in an interface that needs to be implemented, not one method in an interface.
Another new feature in jdk 8 is default, which does not affect the use of Lambda expressions because default-modified methods have default implementations, not methods that must be implemented.

4.@FunctionalInterface Annotation Role

The @FunctionalInterface tag is on an interface, and a functional interface is an interface that contains only one abstract method.

2. Lambda expression syntax

1. Grammatical Structure


The syntax is () -> {}, where () describes the parameter list, {} describes the method body, -> is the lambda operator, read as (go to).

2. Important features of Lambda expressions

Optional type declaration: There is no need to declare parameter types, and the compiler can universally identify parameter values.
Optional parameter parentheses: One parameter does not need to define parentheses, but multiple parameters need to define parentheses.
Optional braces: If the body contains a statement, braces are not required.
Optional return keyword: If the body has only one return value from an expression, the compiler automatically returns the value, and the braces need to specify that the explicit expression returns a numeric value.

3.Lambda case

3. Introduction cases of Lambda expression

1. Define function interfaces

//Introduction to Lambda Expression Case_ Define function interfaces
//No return value, no parameters
@FunctionalInterface
interface NoReturnNoParam{
    void method();
}

//No return value, one parameter
@FunctionalInterface
interface NoReturnOneParam{
    void method(int a);
}

//No return value, multiple parameters
@FunctionalInterface
interface NoReturnMultiParam{
    void method(int a,int b);
}

//Return value, no parameters
@FunctionalInterface
interface ReturnNoParam{
    int method();
}

//Has a return value, has a parameter
@FunctionalInterface
interface ReturnOneParam{
    int method(int a);
}

//Has a return value, has multiple parameters
@FunctionalInterface
interface ReturnMultiParam{
    int method(int a,int b);
}

public class Test {
}

2. Implement Function Interface

public class Test {
    //Introduction to Lambda Expression Case_ Implement Function Interface
    public static void main(String[] args) {
        //Implement no return value, no parameter interface
        NoReturnNoParam noReturnNoParam = ()->{
            System.out.println("NoReturnNoParam");
        };
        noReturnNoParam.method();

        //Implement no return value with a parameter interface
        NoReturnOneParam noReturnOneParam = (int a)->{
            System.out.println("NoReturnOneParam  "+a);
        };
        noReturnOneParam.method(1);

        //Implement no return value, multiple parameter interfaces
        NoReturnMultiParam noReturnMultiParam =(int a,int b)->{
            System.out.println("NoReturnMultiParam  "+a+"  "+b);
        };
        noReturnMultiParam.method(1,2);

        //Implement a return value, no parameter interface
        ReturnNoParam returnNoParam = ()->{
            System.out.println("ReturnNoParam");
            return 10;
        };
        System.out.println(returnNoParam.method());

        //Implementation has a return value and a parameter interface
        ReturnOneParam returnOneParam = (int a)->{
            System.out.println("ReturnOneParam");
            return a;
        };
        System.out.println(returnOneParam.method(20));

        //Implementation has a return value and multiple parameter interfaces
        ReturnMultiParam returnMultiParam = (int a,int b)->{
            System.out.println("ReturnMultiParam" );
            return a+b;

        };
        System.out.println(returnMultiParam.method(10,20));
    }
}

3.Lambda syntax simplification

Simplified version

/*Simplified version*/
public class Test {
    //Introduction to Lambda Expression Case_ Implement Function Interface
    public static void main(String[] args) {
        //Implement no return value, no parameter interface
        NoReturnNoParam noReturnNoParam = ()-> System.out.println("NoReturnNoParam");
        noReturnNoParam.method();

        //Implement no return value with a parameter interface
        NoReturnOneParam noReturnOneParam = a-> System.out.println("NoReturnOneParam  "+a);
        noReturnOneParam.method(1);

        //Implement no return value, multiple parameter interfaces
        NoReturnMultiParam noReturnMultiParam =(a,b)-> System.out.println("NoReturnMultiParam  "+a+"  "+b);
        noReturnMultiParam.method(1,2);

        //Implement a return value, no parameter interface
        ReturnNoParam returnNoParam = ()->{
            System.out.println("ReturnNoParam");
            return 10;
        };
        System.out.println(returnNoParam.method());

        //Implementation has a return value and a parameter interface
        ReturnOneParam returnOneParam = a->{
            System.out.println("ReturnOneParam");
            return a;
        };
        System.out.println(returnOneParam.method(20));

        //Implementation has a return value and multiple parameter interfaces
        ReturnMultiParam returnMultiParam = (a,b)->{
            System.out.println("ReturnMultiParam" );
            return a+b;

        };
        System.out.println(returnMultiParam.method(10,20));
    }
}

4. Use of Lambda expressions

1. Reference Method

Sometimes we don't have to use Lambda's function body definition to implement it, we can use the lambda expression to refer to
To a method that has already been implemented.
The syntax is as follows:
Method attributors: Static method attributors are class names, and common method attributors are objects.
Example of using an external method as an implementation of an abstract method of a function interface:

public class Test2 {
    public static void main(String[] args) {
        ReturnOneParam returnOneParam = a -> doubleNum(a);
        int value = returnOneParam.method(10);
        System.out.println(value);
    }
    /*
    * Requirements for using an external method as an implementation of an abstract method of a function interface:
    * 1.The number and type of parameters need to be consistent with the abstract method in the function interface.
    * 2.The return value type should be the same as the return value type of the abstract method in the function interface.*/
    public static int doubleNum(int a){
        return 2*a;
    }
}

If the method is not in this class, the syntax structure is:
z method attributor: method name static method attributor is class name, common method attributor is object.
Static method public static int doubleNum (int a) {return 2*a;} Static methods are owned by class names:

ReturnOneParam returnOneParam =  Test::doubleNum;

Non-static method public int addTwo(int a) {return a+2;} The common method owner is the object:
Need a new object first:

//Non-static methods instantiate objects first
        Test test = new Test();
        ReturnOneParam returnOneParam1 = test::addTwo;
        int value1 = returnOneParam1.method(10);
        System.out.println(value1);

2. Create Threads

In Java multi-threaded, there are two ways to create threads. The first is to define our thread class by inheriting the Thread class and overriding the run method inside. The second way is to implement the Runnable interface and then the run method within it.

There is only one abstract method in Runnable that fits the definition of our function interface, so Lammbda expressions can be used to implement the abstract method in this interface.
Therefore, the purpose of Lambda expression is to implement the run method in the Runnable interface.

The code is as follows:

//Use of Lambda Expression_ Create Threads
public class Test3 {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"  start");
        /*
        * new Thread(a,"b")The first argument to the method is a reference to the current interface implementation class
        * You can also give the current thread a name as the second parameter*/
        //Mode 1:
//        Runnable runnable = ()->{};
//        new Thread(runnable,"Lambda Thread ").start();;
        //Short form:
        new Thread(()->{
            //Braces define what the child threads do, which is represented here by a print statement
            for(int i=0;i<20;i++){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" "+i);
            }

        },"Lambda Thread ").start();
        System.out.println(Thread.currentThread().getName()+"  End");
        //The purpose of Lambda expression is to implement the run method in the Runnable interface.
    }
}

3. Traversal set of operation sets

public class Test4 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.forEach(System.out::println);
    }
}

Click to view detailed instructions

4. Delete element of operation set

Keywords: Java Back-end

Added by Kaizard on Tue, 25 Jan 2022 20:26:51 +0200