Java Fundamentals Summary 1.8 new features lambda expressions

Source: Internet
Author: User

Function-type interface

The function interface (functional interface is also called the functional 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, an interface that contains only one method), the virtual opportunity is automatically judged, but It is best to use annotation @functionalinterface on the interface to make the declaration so that other people in the team mistakenly add new methods to the interface.
Lambda in Java cannot appear alone, it requires a functional interface to hold, the lambda expression method body is actually the implementation of the function interface, as described in the following syntax.

Lambda Syntax

Consists of three parts

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

    2. An arrow symbol:->

    3. Method body, can be expressions and code blocks, method body function interface inside the implementation of the method, if it is a block of code, it must be wrapped with {}, and need a return value, but with an exception, if the function interface inside the method return value is void, you do not need {}

 Public classTestlambda { Public Static voidRunthreaduselambda () {//runnable is a function interface that contains only a run method that returns void with no parameters;//so there are no arguments on the left side of the lambda expression, no return on the right, just a simple print.        NewThread (()->system.out.println ("Thread implemented by lambda") . Start (); }      Public Static voidRunthreaduseinnerclass () {//this way is not much to say, previous old version of the more common practice        NewThread (NewRunnable () {@Override Public voidrun () {System.out.println ("Threads implemented by internal classes");    }}). Start (); }      Public Static voidMain (string[] args) {testlambda.runthreaduselambda ();    Testlambda.runthreaduseinnerclass (); }}

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

Method Reference

In fact, it is a simplified notation of lambda expression, the method referred to is actually a lambda expression method body implementation, syntax is very simple, the left is a container (can be the class name, instance name), the middle is "::", the right is the corresponding method name.

The reference format for a generic method is

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

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

    3. constructor. It's classname::new.

Take a look at a complete example to facilitate understanding

Importjava.awt.FlowLayout;Importjava.awt.event.ActionEvent;ImportJavax.swing.JButton;ImportJavax.swing.JFrame; Public classTestmethodreference { Public Static voidMain (string[] args) {JFrame frame=NewJFrame (); Frame.setlayout (NewFlowLayout ()); Frame.setvisible (true); JButton button1=NewJButton ("Click me!"); JButton Button2=NewJButton ("Click me!");        Frame.getcontentpane (). Add (button1);        Frame.getcontentpane (). Add (Button2); //the parameter of the addActionListener method here is ActionListener, which is a functional interface//using lambda expressionsButton1.addactionlistener (E, {System.out.println ("Here is how Lambda is implemented");        }); //How to use method referencesButton2.addactionlistener (testmethodreference::d osomething); }    /*** Here is the implementation method of the function interface ActionListener *@parame*/     Public Static voiddosomething (ActionEvent e) {System.out.println ("Here is how the method reference is implemented"); }}

Why lambda expressions are required

There are three main reasons:

> more Compact Code
For example, the existing anonymous inner classes in Java, as well as listeners (listeners) and event handlers (handlers), are very lengthy
> Ability to modify methods (I personally understand code injection, or a bit like JavaScript that passes a callback function to another function)
For example, the contains method of the collection interface returns True if and only if the passed-in element is really contained in the collection. And if we want to set a string, pass in a string, and return True if the string appears in the collection (ignoring the case).
Simply put, what we want is to pass in "some of our own code" into the existing method, and the existing method will execute the code we passed in. Lambda expressions can support this very well,
> Better support for multicore processing
For example, with the addition of a lambda expression in Java 8, we can easily manipulate large collections in parallel, giving full play to the potential of multi-core CPUs.
Parallel processing functions such as filter, map, and reduce.

Summary of Java Fundamentals 1.8 new features lambda expression

Related Article

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.