Home  >  Article  >  Java  >  A brief analysis of Lambda expressions in Java 8: Why use Lambda expressions?

A brief analysis of Lambda expressions in Java 8: Why use Lambda expressions?

不言
不言Original
2018-09-21 11:07:393384browse

The content of this article is about a brief analysis of Lambda expressions in Java 8: why Lambda expressions should be used. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Lambda expressions are the most popular feature of Java8. People introduced the concept of functional programming into Java, a completely object-oriented imperative programming language.

As for how functional programming works, this topic is beyond the scope of this article, but we will extract one of its features that is obviously different from the OOP (object-oriented programming) we often use to discuss. .

In this article, we will learn what exactly lambda expressions are and how they fit themselves into the overall Java ecosystem. We will also observe and compare the code that does not use lambda expressions and the sample code that is refactored later using lambda.

Understanding Lambda Expressions

A Lambda expression is a piece of code that we can pass in and execute. For us as Java programmers, we are not used to passing a piece of code into a function. Our habit is to encapsulate the defined code into the method body, and then execute it through object references, as shown below:

public class LambdaDemo {
    public void printSomething(String something) {
        System.out.println(something);
    }
    public static void main(String[] args) {
        LambdaDemo demo = new LambdaDemo();
        String something = "I am learning Lambda";
        demo.printSomething(something);
    }
}

This is classic OOP development Paradigm style hides method implementation from callers. The caller simply passes a variable into the method, and then the method performs some operations on the variable and returns another variable value, or, as in our example, produces some side effects.

Now we’re going to look at an equivalent implementation that uses behavior passing instead of variable passing. To do this, we need to create a functional interface that defines behavior rather than abstraction of methods. A functional interface is an interface with only one method:

public class LambdaDemo {
    interface Printer {
        void print(String val);
    }
    public void printSomething(String something, Printer printer) {
        printer.print(something);
    }
}

In the above code implementation, the Printer interface is responsible for all printing operations. The printSomething method no longer defines behavior, but executes the behavior defined by Printer:

public static void main(String[] args) {
    LambdaDemo demo = new LambdaDemo();
    String something = "I am using a Functional interface";
    Printer printer = new Printer() {
        @Override
        public void print(String val) {
            System.out.println(val);
        }
    };
    demo.printSomething(something, printer);
}

The more observant readers may have noticed that I Nothing new is done here. This is true because I haven't applied it to lambda expressions yet. We simply create a concrete implementation of the Printer interface and pass it into the printSomething method.

The above example aims to bring us a key goal of introducing Lambda expressions into Java:

Lambda expressions were originally used to define an inline implementation of a functional interface

Before we use lambda expressions to reconstruct the above example, let's learn the necessary syntax knowledge:

(param1,param2,param3...,paramN) - > {//代码块;}

a The composition of a lambda expression is a parameter list enclosed by parentheses and separated by commas, which we usually define in a method declaration, followed by an arrow pointing to the code to be executed. Now, let’s refactor the above code using lambda:

public static void main(String[] args) {
    LambdaDemo demo = new LambdaDemo();
    String something = "I am learning Lambda";
    /**/
    Printer printer = (String toPrint)->{System.out.println(toPrint);};
    /**/
    demo.printSomething(something, printer);
}
}

It looks very compact and beautiful. Because the functional interface declares only one method, the parameters passed in the first part of the lambda are automatically mapped to the method's parameter list, and the code to the right of the arrow is regarded as the specific implementation of the method.

Why use Lambda expressions

As in the previous example, lambda expressions allow us to have more compact code that is easier to read and follow. There are other benefits to this approach in terms of performance and multi-core processing, but they only apply after you understand the Streams API, which is beyond the scope of this article.

By comparing the main method with and without lambda, when it suddenly shortens the code, we can actually see the power of lambda expressions:

public static void main(String[] args) {
    LambdaDemo demo = new LambdaDemo();
    String something = "I am learning Lambda";
    /**/
    Printer printer = (String toPrint)->{System.out.println(toPrint);};
    /**/
    demo.printSomething(something, printer);
}

We can also make the code more concise than what is shown here. When this happens, you don't even need to specify the type of the parameter on the left side of the arrow, and its type will be inferred by the compiler based on the formal parameters of the interface method.

Printer printer = (toPrint)->{System.out.println(toPrint);};

We can do better. Another feature of lambda is that if there is only one parameter, the parentheses can be completely eliminated. Similarly, if there is only one statement to the right of the arrow, you can also remove the curly braces:

Printer printer = toPrint -> System.out.println(toPrint);

The code now looks really cute, but we It's just the beginning. If our interface method does not require any parameters, we can replace the life with an empty pair of brackets:

() -> System.out.println("anything");

If we just inline a lambda What if we go in without first creating an object and passing it into the saySomething method:

public static void main(String[] args) {
    LambdaDemo demo = new LambdaDemo();
    String something="I am Lambda";    /**/
    demo.printSomething(something, toPrint -> System.out.println(toPrint));
}

Now we are really talking about functional programming. Our main function body has been reduced from 9 lines of code to 3 lines. Such compact code makes lambda expressions very attractive to Java programmers.

The above is the detailed content of A brief analysis of Lambda expressions in Java 8: Why use Lambda expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn