New features of Java 8 - Lambda expressions (1)

       Lambda expression is an anonymous function, named after the lambda calculus in mathematics, and can also be called closure. Many languages ​​now support Lambda expressions, such as  C++ , C# , JavaPython  and  JavaScript  . Lambda expressions are an important new feature driving the release of Java 8. They allow functions to be passed as parameters to a method (functions are passed into methods as parameters)

      Let’s understand the concept of Lambda expression through the following example:

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 a classic OOP implementation. Next we make a modification to the above code, create a functional interface, and define abstract methods for the interface.  

public class LambdaDemo {
    //抽象功能接口
    interface Printer {
        void print(String val);
    }
    //通过参数传递功能接口
    public void printSomething(String something, Printer printer) {
        printer.print(something);
    }

    public static void main(String[] args) {
        LambdaDemo demo = new LambdaDemo();
        String something = "I am using a Functional interface";
        //实现Printer接口
        Printer printer = new Printer() {
            @Override
            public void print(String val) {
                //控制台打印
                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. Next, we will refactor the above code using lambda expressions.

Regarding the syntax of lambda expressions:

Formal parameter list => function body (the function body can be enclosed in curly braces if it contains more than one statement). In Java, it is () -> {} :

(param1,param2,param3 ...,paramN)-  > {   //代码块;  }
  • lambda expression, which expresses the interface function
  • To the left of the arrow is the comma-separated list of formal parameters for the function.
  • The right side of the arrow is the code of the function body
package com.example.exceldemo.task;
public class LambdaDemo {
    //抽象功能接口
    interface Printer {
        void print(String val);
    }
    //通过参数传递功能接口
    public void printSomething(String something, Printer printer) {
        printer.print(something);
    }

    public static void main(String[] args) {
        LambdaDemo demo = new LambdaDemo();
        String something = "I am learning Lambda";
        //实现Printer接口(请关注下面这行lambda表达式代码)
        Printer printer = System.out::println;
        //调用接口打印
        demo.printSomething(something, printer);
    }
}

Of course, the two ways of writing are exactly the same:

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

Replenish: 

::After Java 8, the double colon operator        was added , which is used for " method reference ". Note that it is not a method call. Although "method reference" does not directly use Lambda expressions, it is also related to Lambda expressions and functional interfaces. The syntax for a method reference is as follows:

ObjectRef  :: methodName 

       Among them, ObjectRef is the class name or instance name, and methodName is the corresponding method name.

       Method reference can be understood as a shortcut for Lambda expressions. It is more concise, more readable, and has good reusability than Lambda expressions. If the implementation is relatively simple and there are not many places for reuse, it is recommended to use Lambda expressions, otherwise method references should be used.

        Lambda expressions make our code more concise. There are actually more performance and multi-core processing benefits to using lambda expressions, but they only make sense after understanding the Java8 Streams API and are therefore beyond the scope of this article.

        Compared with the implementation of traditional Java code, has the amount of code been reduced a lot? But this is still not the simplest way to implement it, so let’s take it step by step.

Printer printer = (String toPrint)->{System.out.println(toPrint);};
//简化:去掉参数类型
Printer printer = (toPrint)->{System.out.println(toPrint);};
//简化:去掉参数括号
Printer printer = toPrint->{System.out.println(toPrint);};
//简化:去掉函数体花括号
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, we can completely omit the parentheses of the parameter
  • When the function body is only one line, we can completely omit the function body curly braces

If our interface method is defined without any parameters, it can be replaced by empty brackets:

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

So, what does the code we finally simplify through lambda expressions look like? The true face of Mount Lu:


public static void main(String[] args) {
    LambdaDemo demo = new LambdaDemo();
    String something="I am Lambda";
    //关注下面的这行代码
    demo.printSomething(something, toPrint -> System.out.println(toPrint));
}

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

Guess you like

Origin blog.csdn.net/weixin_49171365/article/details/130157534