Java8 new features series Lambda

Posted by jazappi on Wed, 02 Mar 2022 15:14:40 +0100

Reprinted from: Java8 new features series - Lambda - wechat blog

Lambda Expressions in Java 8

Lambda expressions are the most popular feature of Java 8. They introduce the concept of functional programming into Java, a completely object-oriented imperative programming language. The working principle of functional programming language is beyond the scope of this article, but we will extract a feature that is obvious to us using OOP.

In this article, we will learn what lambda expressions are and how they fit into the entire Java ecosystem. We'll also look at the sample code that doesn't use lambda expressions, and then refactor the code to use lambda.

Understand a Lambda expression

Lambda expressions are blocks of code that we can pass and execute. Passing code blocks to functions is something we are not used to as Java programmers. All our behavior definition codes are encapsulated in the method body and executed by object reference, just like using the following code:

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 the classic OOP style of hiding the implementation of the caller method. The caller only needs to pass a variable to the method, and then the method performs some operations on the value of the variable and returns another value or has side effects, just as in our example.

We will now see an equivalent implementation that uses behavior passing instead of variable passing. To achieve this, we must create a functional interface to define abstract behavior rather than methods. 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 implementation, the Printer} interface is responsible for all printing. The printSomething , method no longer defines the 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);
}

Careful people among you may have noticed that we haven't done anything new here. This is true because we haven't applied lambda expressions yet. We simply create a concrete implementation of the # Printer # interface and pass it to the # printSomething # method.

The above demonstration aims to bring us to the key goal of introducing Lambda expressions into Java: Lambda expressions are mainly used to define the inline implementation of functional interfaces.

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

(param1,param2,param3...,paramN) - > {//block of code;}

A lambda forms a comma separated list of formal parameters enclosed in parentheses, as defined in the method declaration, followed by an arrow mark pointing to the code to be executed. Now let's refactor the above code to use 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);
}

Very compact and beautiful. Since the functional interface only declares one method, the parameters passed in the first part of lambda will be automatically mapped to the parameter list of the method, and the code to the right of the arrow is regarded as the specific implementation of the method

Why use Lambda expressions

Like the demonstration in the previous section, lambda expressions enable us to have more compact code that is easier to read and follow. There are other benefits in terms of performance and multi-core processing, but it can only be understood after understanding the Streams API, so it is beyond the scope of this article.

Comparing the main methods of using and not using lambda, we show the powerful function of lambda expression in shortening Code:

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 make our code more concise than this. As it happens, even if the type of the parameter is not specified to the left of the arrow, the compiler infers its type from the formal parameters of the interface method:

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

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

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

Now our code is really starting to look cute. We're just getting started. If our interface method does not take any parameters, we can replace the declaration with empty parentheses:

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

Instead of creating an object and passing it to the saySomething method, let's inline lambda directly:

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 really start talking about functional programming. Our original nine line subject is now reduced to only three lines. The compactness of this code makes lambda expressions very attractive to Java programmers.

Topics: Java Lambda java8