Java SE 8:lambda Expressions

Source: Internet
Author: User
Tags abstract foreach arrays constructor implement new features pear thread

The Java SE 8 has been fully functional in the June 13 version. In these new features, lambda expressions are the most important new features that drive the release of this release. Because Java first tried to introduce the relevant content of functional programming. The community has also been looking forward to lambda expressions for a long time. The content of the lambda expression is defined in JSR 335 and is based on the latest specification and JDK 8 build b94. The development environment uses eclipse.

Lambda expression

To understand lambda expressions, the first thing to understand is a functional interface (functional interface). In simple terms, a functional interface is an interface that contains only one abstract method. For example, Java.lang.Runnable and Java.util.Comparator in the Java Standard library are typical functional interfaces. For functional interfaces, you can use a lambda expression to create an implementation object in addition to using the standard methods in Java to create an implementation object. This simplifies the implementation of the code to a large extent. When you use lambda expressions, you only need to provide form parameters and method bodies. Because functional interfaces have only one abstract method, the body of a method declared through a lambda expression is definitely the implementation of this unique abstract method, and the type of the formal argument can be inferred automatically based on the type declaration of the method.

Using the Runnable interface as an example, the traditional way to create a thread and run it is as follows:

public void Runthread () {
    new Thread (new Runnable () {public
        void run () {
            System.out.println ("run!");
        }
    }). Start ();
}

In the above code, you first need to create an anonymous inner class to implement the Runnable interface, and you need to implement the Run method in the interface. If you use a lambda expression to accomplish the same function, the resulting code is very concise, as shown in the following:

public void 

Runthreaduselambda () {
    new Thread (()-> {
        System.out.println ("run!");
    }). Start ();
}

In the traditional way, lambda expressions are simplified in two ways: first, the declaration of the Runnable interface, which can be inferred from the context environment, followed by the implementation of the Run method, because the functional interface contains only one method that needs to be implemented.

A lambda expression is declared in a relatively simple way, consisting of two parts of a formal parameter and a method body, separated by "->" in the middle. Formal parameters do not need to contain type declarations and can be inferred automatically. Of course, in some cases, the type declarations of formal arguments are essential. The method body can be a simple expression or block of code.

For example, putting an integer list in descending order can be accomplished with the following code:

Collections.sort (list, (x, y)-> y-x);

The lambda expression "(x, y)-> y-x" implements the Java.util.Comparator interface.

The standard library before Java SE 8 contains not many functional interfaces. Java SE 8 adds java.util.function packages, which are functional interfaces that can be used in development. Developers can also create new functional interfaces. 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 following code uses the method implemented by the functional interface java.util.function.Function to map operations to a list. As you can see from the code, if you use functional interfaces as much as possible, your code will be very concise.

public class 

Collectionutils {public
    static  list map (List input, Function processor) {
        ArrayList result = new ArrayList ();
        for (T obj:input) {
            result.add (processor.apply (obj));
        }
        return result;
    }
    
    public static void Main (string[] args) {
        List input = arrays.aslist (new string[] {"Apple", "orange", "Pear"});
        List lengths = Collectionutils.map (input, (String v)-> v.length ());
        List uppercases = Collectionutils.map (input, (String v)-> v.touppercase ());
    }

Methods and construction method references

A method reference can refer to a method without invoking a method. A constructor reference can refer to a construction method without creating an object. Method references are another way to implement functional interfaces. In some cases, the method reference can further simplify the code. For example, in the following code, the first foreach method invocation uses a lambda expression and the second uses a method reference. They work the same way, but using method references is more concise.

List input = Arrays.aslist

(new string[] {"Apple", "orange", "Pear"});
Input.foreach ((v)-> System.out.println (v));
Input.foreach (System.out::p rintln);

The constructor can be referenced by the name "new", as shown in the following code:

List datevalues = 

arrays.aslist (new long[] {0L, 1000L});
List dates = Collectionutils.map (datevalues, date::new);

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.