A brief analysis of lambda expression of new Java8 characteristics _java

Source: Internet
Author: User
Tags instance method advantage

When it comes to Java 8, the first thing you'll think of is lambda (closures) and virtual extension methods (default method), which has already been abuzz by the big technology sites and the first feature of our Java 8 Series (JEP126 http:// openjdk.java.net/jeps/126), some libraries in JDK8 have been redesigned with lambda expressions to understand that he is important for learning the new Java 8 features.

A function of the interface

Functional interface (functional interface is also called the function interface, is actually 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 annotations, this annotation is not necessary, as long as the interface conforms to the standard of the functional interface (that is, the interface that contains only one method), the virtual opportunity to automatically judge, but It is a good idea to use the annotation @functionalinterface on an interface to make a declaration so that other people in the team incorrectly add new methods to the interface.
The lambda in Java cannot appear alone, it needs a functional interface to hold it, and the lambda expression method body is actually the implementation of the function interface, which is described in the following syntax

Second, lambda syntax

Contains three parts

1. A comma-delimited form parameter in parentheses, which is the parameter of a method inside a function interface.

2. An arrow symbol:->

3. Method body, can be expression and code block, method body function interface inside the implementation of the method, if it is a code block, you must use {} to wrap up, and need a return value, but there is an exception, if the function interface inside the method return value is void, you do not need to {}

Overall it looks like this:

Copy Code code as follows:

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


See a complete example to facilitate understanding

Copy Code code as follows:

/**
* Test lambda expression
*
* @author Benhail
*/
public class Testlambda {

public static void Runthreaduselambda () {
Runnable is a function interface that contains only a parameterless, return void Run method;
So the lambda expression has no parameters to the left, no return on the right, just a simple word.
New Thread (()->system.out.println ("Thread implemented by Lambda"). Start ();
}

public static void Runthreaduseinnerclass () {
This is not much to say, the previous version of the more common practice
New Thread (New Runnable () {
@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("Thread of inner class implementation");
}
). Start ();
}

public static void Main (string[] args) {
Testlambda.runthreaduselambda ();
Testlambda.runthreaduseinnerclass ();
}
}

As you can see, code designed with lambda expressions is more concise and readable.

Third, method reference

In fact, a lambda expression of a simplified way, the reference method is actually a lambda expression of the method body implementation, syntax is very simple, the left side is the container (can be the class name, instance name), the middle is "::", the right is the corresponding method name. As shown below:

Copy Code code as follows:
Objectreference::methodname

The general method's reference format is

If it is a static method, it is classname::methodname. As Object:: Equals

If it is an instance method, it is instance::methodname. such as Object Obj=new object (); obj::equals;

constructor. It's classname::new.

Let's look at a complete example to facilitate understanding:

Copy 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 ("Point me!");
JButton button2 = new JButton ("Also point me!");

Frame.getcontentpane (). Add (button1);
Frame.getcontentpane (). Add (Button2);
The parameter of the addActionListener method here is ActionListener, which is a function-type interface
Using lambda expression methods
Button1.addactionlistener (e-> {System.out.println ("Here is the lambda implementation Method");
Use method Reference Way
Button2.addactionlistener (testmethodreference::d osomething);

}
/**
* Here is the implementation method of functional interface ActionListener
* @param E
*/
public static void DoSomething (ActionEvent e) {

System.out.println ("Here is the method reference implementation Way");

}
}


As you can see, the DoSomething method is the implementation of lambda expressions, and the advantage of this is that if you think that the lambda method is very long and affects the readability of the code, the method reference is a solution.

Iv. Summary

The above is the entire content of lambda expression syntax, I believe you have a certain understanding of lambda expression, but only the code concise this advantage, and can not impress many viewers, Java 8 will not be so expected, in fact, Java 8 the urgent need to introduce lambda is because lambda expressions can simplify the multithreading or multi-core processing of data on the collection. Provides faster collection processing speed, this follow-up will say, about the JEP126 of this feature, will be divided into 3 parts, because this feature can write too many things, This section allows the reader to familiarize itself with the syntax and concepts of lambda expressions and method references, the second part is the content of the virtual extension methods (default method), and the last part is the processing of large data sets that unlock the most powerful mysteries of lambda expressions. Please look forward to ....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.