Comparing lambda expression with traditional interface function

Posted by dandare on Fri, 08 Nov 2019 01:53:05 +0100

In some articles written before this number, the author used lambda expression syntax, some readers reported that the code could not be understood.I thought java 13 was already out. The most important feature of lambda expressions in java 8 should be well understood. In fact, there are still a large number of programmers who do not use java 8, and there are also java 8 programmers who do not use lambda expressions.So it is still necessary to write this article. If you find my article helpful to you, we look forward to your attention.

Lambda expressions are the most popular and commonly used feature of Java 8.It introduces the concept of functional programming into Java. The advantage of functional programming is that it can help us save a lot of code, is very easy to use, and can greatly improve our coding efficiency.In this article, we will introduce what lambda expressions are and convert the traditional java code writing to lambda expression writing, so you can see through examples how lambda expressions simplify the traditional code.

1. Interface Definition

First, we need to understand what the lambda expression is expressing?The answer is that lambda expressions express the implementation of interface functions, so we need to do some preparatory work.In traditional development, we are not accustomed to passing code blocks to functions.All of our behavior definition code is encapsulated within the method body and executed through object references, just like the code below:

public class LambdaDemo {
    //Function Definition
    public void printSomething(String something) {
        System.out.println(something);
    }
    //Calling functions by creating objects
    public static void main(String[] args) {
        LambdaDemo demo = new LambdaDemo();
        String something = "I am learning Lambda";
        demo.printSomething(something);
    }
}

You should be familiar with how the above code was developed, which is a classic implementation style of OOP.Let's make a modification to the above code to create a functional interface and define an abstract method for that interface.

public class LambdaDemo {
    //Abstract function interface
    interface Printer {
        void print(String val);
    }
    //Pass Functional Interface Through Parameters
    public void printSomething(String something, Printer printer) {
        printer.print(something);
    }
}

2. Traditional implementation of interface functions

In the above implementations, the Printer interface is responsible for printing behavior, either console printing or other printing behavior.The method printSomething no longer defines behavior, but rather implements Printer-defined behavior, which makes the design more flexible.The code is as follows:

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

At this point, we have not used lambda expressions.We have only created a concrete implementation of the Printer interface and passed it to the printSomething method.

3. Implementation of lambda expression

As for the concept of lambda expressions, let's first learn the syntax of lambda expressions:

(param1,param2,param3 ...,paramN)-  > {   //Code block;}
  • First we know the lambda expression, which is an interface function
  • To the left of the arrow is a comma-separated list of formal parameters for the function
  • To the right of the arrow is the body code

Now let's refactor the code in the first section using lambda expressions

public static void main(String[] args) {
    LambdaDemo demo = new LambdaDemo();
    String something = "I am learning Lambda";
    //Implement the Printer interface (follow this line of lambda expression code)
    Printer printer = (String toPrint)->{System.out.println(toPrint);};
    //Invoke Interface Printing
    demo.printSomething(something, printer);
}

Lambda expressions make our code more concise.In fact, lambda expressions have more performance and multicore benefits, but they are meaningful only after you understand the java8 Streams API and are therefore not covered in this article (as described in previous articles).

Does the amount of code decrease a lot compared to how traditional java code is implemented?But this is still not the simplest way to do it. Let's go step by step.

Printer printer = (String toPrint)->{System.out.println(toPrint);};
//Simplification: Remove parameter types
Printer printer = (toPrint)->{System.out.println(toPrint);};
//Simplification: Remove parameter brackets
Printer printer = toPrint->{System.out.println(toPrint);};
//Simplification: Remove function body curly brackets
Printer printer = toPrint->System.out.println(toPrint);
  • Even if the type of the parameter is not specified on the left side of the arrow, the compiler will infer its type from the formal parameters of the interface method
  • When there is only one parameter, parentheses can be omitted
  • When the body of a function has only one line, we can completely omit the curly brackets

If our interface method definition does not take any parameters, you can replace it with empty parentheses:

()->  System.out.println("anything you wan to print")

So what is the code that we ultimately simplify with a lambda expression?Lushan Real Face:

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

Using lambda expressions inline as function call parameters, we reduced the 9 lines of code of the original main method to only 3 lines.However, the author wants to say that this is still not the ultimate pole code simplification that lambda expressions can do. When you learn the java8 Stream API combined with lambda expressions, you will find that your coding efficiency will be greatly improved!

conclusion

The lambda expression represents an interface function, the function parameters are on the left side of the arrow, and the function body is on the right side of the arrow.The parameter type and return value type of the function can be omitted, and the program automatically determines the data type based on the context of the interface definition.

In this article, we give a detailed introduction to Lambda expressions in Java and learn how to use them to improve the efficiency and quality of interface implementation.Keep an eye on this number for more information, and the Stream API, when used with the Collections framework, provides Lambda with additional benefits.

Looking forward to your attention

Topics: Java Lambda Programming SpringBoot