Speaking of Java 8, the first thing that comes to mind is lambda (closure) and virtual extension method (default method). This feature has long been hyped by major technology websites, and it is also the first feature we will talk about at the beginning of our Java 8 series (JEP126 http://openjdk.java.net/jeps/126), some libraries of jdk8 have been redesigned using lambda expressions. Understanding it is of great significance to learning the new features of java 8.
1. Functional interface
Functional interface (functional interface is also called functional interface, but it is actually the same thing). Simply put, 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 necessary. As long as the interface meets the standards of functional interfaces (that is, an interface that only contains one method), the virtual machine will automatically determine it. However, it is best to use the annotation @FunctionalInterface on the interface to declare it. This prevents other people on the team from mistakenly adding new methods to the interface.
Lambda in Java cannot appear alone. It requires a functional interface to hold it. The lambda expression method body is actually the implementation of the functional interface. The syntax will be discussed below.
2. Lambda syntax
Contains three parts
1. A formal parameter separated by commas in parentheses. The parameter is the parameter of the method in the functional interface.
2. An arrow symbol: ->
3. The method body can be an expression or a code block. The method body is the implementation of the method in the functional interface. If it is a code block, it must be wrapped with {} and a return value is required, but there is an exception. If If the method return value in a functional interface is void, {} is not needed.
Overall it looks like this:
Copy the code code as follows:
(parameters) -> expression or (parameters) -> { statements; }
See a complete example for easy understanding
Copy the code code as follows:
/**
* Test lambda expression
*
* @author benhail
*/
public class TestLambda {
public static void runThreadUseLambda() {
//Runnable is a function interface that only contains a parameterless run method that returns void;
//So there are no parameters on the left side of the lambda expression and no return on the right side. It just prints a sentence.
new Thread(() ->System.out.println("thread implemented by lambda")).start();
}
public static void runThreadUseInnerClass() {
//I won’t talk much about this method. It was a common approach in old versions.
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread implemented by internal class");
}
}).start();
}
public static void main(String[] args) {
TestLambda.runThreadUseLambda();
TestLambda.runThreadUseInnerClass();
}
}
It can be seen that the code designed using lambda expressions will be more concise and readable.
3. Method reference
In fact, it is a simplified way of writing lambda expression. The referenced method is actually the method body implementation of lambda expression. The syntax is also very simple. The left side is the container (can be a class name or instance name), the middle is "::", and the right side is is the corresponding method name. As shown below:
Copy the code as follows: ObjectReference::methodName
The general method citation format is
If it is a static method, it is ClassName::methodName. Such as Object::equals
If it is an instance method, it is Instance::methodName. Such as Object obj=new Object();obj::equals;
Constructor. It is ClassName::new
Let’s look at a complete example for easier understanding:
Copy the code code as follows:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* @author benhail
*/
public class TestMethodReference {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setVisible(true);
JButton button1 = new JButton("Click me!");
JButton button2 = new JButton("Click me too!");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
//The parameter of the addActionListener method here is ActionListener, which is a functional interface
//Use lambda expression method
button1.addActionListener(e -> { System.out.println("Here is the Lambda implementation"); });
//Use method reference method
button2.addActionListener(TestMethodReference::doSomething);
}
/**
* Here is the implementation method of the functional interface ActionListener
* @param e
*/
public static void doSomething(ActionEvent e) {
System.out.println("Here is the method reference implementation");
}
}
It can be seen that the doSomething method is the implementation of the lambda expression. The advantage of this is that if you feel that the lambda method is very long and affects the readability of the code, method reference is a solution.
4. Summary
The above is the entire content of lambda expression syntax. I believe everyone has a certain understanding of lambda expressions. However, if the code is simple, it will not impress many viewers. Java 8 will not be so exciting. In fact, The urgent need to introduce lambda in java 8 is because lambda Expressions can simplify multi-threaded or multi-core processing of data on a collection and provide faster collection processing speed. This will be discussed later. This feature of JEP126 will be divided into three parts. The reason for the separation is because of this feature. There are too many things to write. This part makes readers familiar with the syntax and concepts of lambda expressions and method references. The second part is about the content of virtual extension methods (default methods). The last part is about the processing of large data collections and solutions. Uncover the power of lambda expressions. Stay tuned. . . .