Brief analysis of Lambda expressions for new Java8 features

  • 2020-04-01 03:22:29
  • OfStack

Said to Java 8, the first thought of lambda (closures) and virtual extension methods (the default method), this feature has been the major technology website fry over, is also our Java 8 series begins with the first feature to tell JEP126 (http://openjdk.java.net/jeps/126), some libraries jdk8 lambda expressions has been applied to the design, understanding of his learning Java 8 new features has important significance.

I. functional interface

A functional interface is the same thing. In simple terms, a functional interface is an interface that contains only one method. For example, java.lang.Runnable and java.util.Comparator in the Java standard library are typical functional interfaces. Java 8 provides @functionalinterface as an annotation. This annotation is not required, as long as the interface meets the standard of functional interfaces (that is, the interface that contains only one method), the virtual machine will automatically determine, but it is best to declare using the annotation @functionalinterface on the interface, lest the rest of the team mistakenly add new methods to the interface.
Lambda in Java cannot be seen alone. It needs a functional interface to be used. The body of a lambda expression method is an implementation of a functional interface

Lambda syntax

It has three parts

1. A comma-delimited formal argument in parentheses that is the argument to a method in a functional interface

2. An arrow symbol: ->

Method body, can be an expression and code block, method body function interface inside the method implementation, if it is a code block, it must be wrapped with {}, and need a return return value, but there is an exception, if the method return value in the functional interface is void, it does not need {}

The whole thing looks like this:


(parameters) -> expression  or  (parameters) -> { statements; }


Let's look at a complete example, just to understand



public class TestLambda {
    public static void runThreadUseLambda() {
        //Runnable is a functional interface that contains only a run method that returns void with no arguments.
        //So the lambda expression has no arguments on the left and no return on the right, just a single printed sentence
        new Thread(() ->System.out.println("lambda Implemented thread ")).start(); 
    }
    public static void runThreadUseInnerClass() {
        //I'm not going to go into this, which is what the old version used to do
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(" Inner class implementation thread ");
            }
        }).start();
    }
    public static void main(String[] args) {
        TestLambda.runThreadUseLambda();
        TestLambda.runThreadUseInnerClass();
    }
}

As you can see, the code designed using lambda expressions is much cleaner and readable.

Method reference

The syntax is also very simple. On the left is the container (can be the class name, instance name), in the middle is "::", and on the right is the corresponding method name. As follows:

ObjectReference::methodName

The general method reference format is

If it's a static method, it's ClassName::methodName. Such as Object: : equals

If it's an Instance method, it's Instance::methodName. If the Object obj = new Object (); Obj: : equals;

The constructor is ClassName::new

Let's look at a complete example to understand:


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;

public class TestMethodReference {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setVisible(true);

        JButton button1 = new JButton(" Am I !");
        JButton button2 = new JButton(" Also let me !");

        frame.getContentPane().add(button1);
        frame.getContentPane().add(button2);
        //The addActionListener method takes an ActionListener, which is a functional interface
        //Use lambda expressions
        button1.addActionListener(e -> { System.out.println(" Here is the Lambda implementation "); });
        //Use method references
        button2.addActionListener(TestMethodReference::doSomething);

    }
    
    public static void doSomething(ActionEvent e) {

        System.out.println(" Here is how the method reference is implemented ");

    }
}


As you can see, the doSomething method is an implementation of lambda expressions, and the nice thing about this is that if you think lambda methods are going to be long and affect code readability, method references are a solution

Four,

Above is all there is in a lambda expression syntax, believe that everyone has certain understanding to lambda expressions, but just the code concise the benefits, and can't move a lot of audience, wouldn't be so exciting, Java 8 actually Java 8 introducing lambda urgent demand because lambda expressions can simplify data collection on multi-threaded or multi-core processing, provides a collection of faster processing speed, the subsequent will say, this feature about JEP126, points is divided into three parts, the separate, Because there is so much to write about, this section familiarzes the reader with the syntax and concepts of lambda expressions and method references, the second section is on the virtual extension method (default method), and the last section is on the processing of big data sets, uncovering the powerful power of lambda expressions. Stay tuned...


Related articles: