IMHO you may not really java part 1: will lambda expressions be used?

Posted Jun 16, 20205 min read

file

The supporting video of this article: B station viewing address

In some articles written before this issue, the author used lambda expression syntax, and some readers reported that the code could not be understood. I thought that Java 13 has already been released. You should have mastered the most important feature of java 8 lambda expressions. In fact, there are still a large number of programmers who do not use java8, and some use java8 will not use lambda expressions.

Lambda expressions are the most popular and commonly used features 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 convenient and easy to use, and can greatly improve our coding efficiency. In this article, we will introduce what lambda expressions are and convert traditional java code writing to lambda expression writing. You can understand through examples how lambda expressions simplify traditional code.

The supporting video of this article: B station viewing address

One, interface definition

First of all, we have to understand what lambda expression is expressing? The answer is the implementation of lambda expression interface functions, so we need to do some preparations. In the traditional way of development, we are not used to passing code blocks to functions. All of our behavior definition code is encapsulated in the method body and executed by object reference, just like using the following code:

public class LambdaDemo {
    //Function definition
    public void printSomething(String something) {
        System.out.println(something);
    }
    //Call the function by creating an object
    public static void main(String[]args) {
        LambdaDemo demo = new LambdaDemo();
        String something = "I am learning Lambda";
        demo.printSomething(something);
    }
}

Everyone should not be unfamiliar with the development of the above code, this is the classic OOP implementation style. Below we make a modification to the above code, create a functional interface, and define abstract methods for the interface.

public class LambdaDemo {
    //Abstract function interface
    interface Printer {
        void print(String val);
    }
    //Parameter passing function interface
    public void printSomething(String something, Printer printer) {
        printer.print(something);
    }
}

The supporting video of this article: B station viewing address

Second, the traditional interface function implementation

In the above implementation, the Printer interface is responsible for printing behavior, which can be console printing or other printing behaviors. The method printSomething no longer defines the behavior, but executes the behavior defined by Printer, this design is more flexible. code show as below:

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

So far we have not used lambda expressions. We only created a concrete implementation of the Printer interface and passed it to the printSomething method.

Three, lambda expression implementation

Regarding the concept of lambda expression later, let's first learn the syntax of lambda expression:

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

  • First of all, we know the lambda expression, which expresses the interface function
  • To the left of the arrow is a comma-separated list of formal parameters of the function
  • The right side of the arrow is the function body code

Now, we use lambda expression to refactor the code in the first section

public static void main(String[]args) {
    LambdaDemo demo = new LambdaDemo();
    String something = "I am learning Lambda";
    //Implement the Printer interface(please pay attention to the following line of lambda expression code)
    Printer printer =(String toPrint)->{System.out.println(toPrint);};
    //Call the interface to print
    demo.printSomething(something, printer);
}

Lambda expressions make our code more concise. In fact, the use of lambda expressions has more benefits in performance and multi-core processing, but they only make sense after understanding the java8 Streams API, so they are not within the scope of this article(the previous articles have been introduced).

Compared with the implementation of traditional java code, is the amount of code reduced a lot? But this is still not the simplest way to achieve, we step by step.

Printer printer =(String toPrint)->{System.out.println(toPrint);};
//Simplify:remove the parameter type
Printer printer =(toPrint)->{System.out.println(toPrint);};
//Simplify:remove parameter brackets
Printer printer = toPrint->{System.out.println(toPrint);};
//Simplify:remove the curly brackets of the function body
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 parameter of the interface method
  • When there is only one parameter, we can omit the parentheses of the parameter
  • When the function body has only one line, we can omit the function body curly brackets

If our interface method definition takes no parameters, we can replace it with empty brackets:

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

So, what does the simplified code look like through lambda expressions? The true face of Lushan:

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

We use lambda expressions inline as function call parameters, reducing the original 9 lines of code to only 3 lines in the main method. But I want to say that this is still not the ultimate code simplification that lambda expressions can accomplish. When you learn the use of java8 Stream API in combination with lambda expressions, you will find that your coding efficiency will be greatly improved!

in conclusion

The lambda expression expresses the interface function, the left side of the arrow is the function parameter, and the right side of the arrow is the function body. Both the parameter type and the return value type of the function can be omitted, and the program automatically determines the data type according to the context defined by the interface.

In this article, we gave a detailed introduction to Lambda expressions in Java and learned how to use them to improve the efficiency and quality of interface implementation. Please pay attention to this number for more content. The Stream API provides more advantages for Lambda when used with the Collections framework.

Welcome to follow my blog, there are many boutique collections

  • This article is reprinted and indicated the source(must be connected, not just text): Alphabet Blog .

If you find it helpful, please like and share it with me! Your support is my endless creative motivation!. In addition, the author has recently output the following fine content, looking forward to your attention.