In case you don’t believe me, I just received a notice from the property management that the epidemic prevention and control has been upgraded. Vehicles can only go out but not in. Each family can assign one member to go shopping for daily necessities every day. This is not a rumor, cut the picture to prove his innocence, from Luoyang City, Hubei Road street.

This may seem like a good idea, but not necessarily a good thing. More people will go to the overtime buying. I don’t care. I’m just gonna stay home and play the long game. During this time, I would like to share some original articles with you — I am blessed to have more knowledge, which will definitely come in handy after the epidemic is over. Today’s topic to share is “Lambda Expressions”, which is also strongly requested by some readers to write before. Sorry for keeping you waiting, is it too late to meet you?

01. First acquaintance with Lambda

A Lambda expression describes a block of code (or anonymous method) that can be passed as an argument to a constructor or normal method for subsequent execution. Consider this code:

() -> System.out.println("Silent King II.")

Copy the code

To explain from left to right, () is the argument list of a Lambda expression (no arguments in this case), -> identifies this code as a Lambda expression (that is, it is Lambda if you see ->), System.out.println(” Silent King ii “) prints “Silent King II” to the standard output stream for the code to execute.

The Runnable interface is a basic interface for multithreading. It is defined as follows:

@FunctionalInterface

public interface Runnable

{

   public abstract void run(a);

}

Copy the code

The Runnable interface is very simple, with just one abstract method run(); If you are careful, you will find a strange annotation @functionalInterface. What does this annotation mean?

I looked at the source code and there was a comment like this:

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

Basically, an interface tagged with @FunctionalInterface can create instances of Lambda expressions. How do you do that?

We created a thread and started it like this:

public class LamadaTest {

    public static void main(String[] args) {

        new Thread(new Runnable() {

            @Override

            public void run(a) {

                System.out.println("Silent King II.");

            }

        }).start();

    }

}

Copy the code

What about Lambda expressions? All you need is the following:

public class LamadaTest {

    public static void main(String[] args) {

        new Thread(() -> System.out.println("Silent King II.")).start();

    }

}

Copy the code

Isn’t it wonderful? Lambda expressions are not only easier to understand than anonymous inner classes, they greatly simplify the amount of code you have to write.

02, Lambda syntax

Each Lambda expression follows the following rules:

( parameter-list ) -> { expression-or-statements }

Copy the code

Parameter-list in () is a comma-separated argument. You may or may not specify the type of the argument (the compiler will infer from the context). After Java 11, you can also use the var keyword as a parameter type, which has a JavaScript flavor.

-> Lambda equivalent identifier, as if to see the imperial edict to see the emperor.

The expression-or-statements in {} are the body of a Lambda and can be one or more lines.

Lambda expressions can do a lot of things, for example

1) Assign values to variables as shown in the following example:

Runnable r = () -> { System.out.println("Silent King II."); };

r.run();

Copy the code

2) As a return result, the following is an example:

static FileFilter getFilter(String ext)

{

    return (pathname) -> pathname.toString().endsWith(ext);

}

Copy the code

3) As an array element, as shown below:

final PathMatcher matchers[] =

{

        (path) -> path.toString().endsWith("txt"),

        (path) -> path.toString().endsWith("java")

};

Copy the code

4) As a parameter to a normal method or constructor, as shown in the following example:

new Thread(() -> System.out.println("Silent King II.")).start();

Copy the code

Note the scope of the Lambda expression.

public static void main(String[] args) {



    int limit = 10;

    Runnable r = () -> {

        int limit = 5;

        for (int i = 0; i < limit; i++)

            System.out.println(i);

    };

}

Copy the code

The above code will compile with an error: the limit variable is already defined.

As with anonymous inner classes, do not make changes to local variables within a method within the body of a Lambda expression or the compilation will fail: variables used ina Lambda expression must be final.

03. Lambda and this

Unlike anonymous inner classes, Lambda expressions do not introduce new scopes. That is, the this keyword used in the body of the Lambda expression is the same as the instance of its class.

Consider the following example.

public class LamadaTest {

    public static void main(String[] args) {

        new LamadaTest().work();

    }



    public void work(a) {

        System.out.printf("this = %s%n".this);



        Runnable r = new Runnable()

        {

            @Override

            public void run(a)

            
{

                System.out.printf("this = %s%n".this);

            }

        };

        new Thread(r).start();

        new Thread(() -> System.out.printf("this = %s%n".this)).start();

    }

}

Copy the code

Tips: %s represents the current output string and %n represents a newline character. You can also use \n instead, but %n is cross-platform.

The code in the work() method can be broken down into three parts:

1) The this keyword alone

System.out.printf("this = %s%n".this);

Copy the code

Where this is the LamadaTest object created with the new keyword in the main() method — new LamadaTest().

2) This keyword in the anonymous inner class

Runnable r = new Runnable()

{

    @Override

    public void run(a)

    
{

        System.out.printf("this = %s%n".this);

    }

};

Copy the code

Where this is the Runnable object created by the new keyword in the work() method — new Runnable(){… }.

3) This keyword in the Lambda expression

Where this keyword is the same as 1).

Let’s look at the output of the program:

this = com.cmower.java_demo.journal.LamadaTest@3feba861

this = com.cmower.java_demo.journal.LamadaTest$1@64f033cb

this = com.cmower.java_demo.journal.LamadaTest@3feba861

Copy the code

It fits the expectations of our analysis.

04, finally

While Lambda expressions do an amazing amount of work to simplify Java programming, improper use can still lead to unnecessary confusion in some cases, and should be used with caution.

Well, my dear readers, that’s all for this article. Can insist to see the technical article during the epidemic, two elder brother must stretch out a thumb for you to point a thumbs-up 👍, after the epidemic, I believe your talent will undoubtedly show.

Originality is not easy, if you feel a little useful, please don’t be stingy with the power of “like” in your hands — because this will be the strongest motivation for my writing.