JAVA 8 Lambda Expressions-Lambda Expressions, lambda-lambda

Source: Internet
Author: User

JAVA 8 Lambda Expressions-Lambda Expressions, lambda-lambda
Lambda expressions

Lambda expressions are defined in java standard proposal JSR 335. Java 8 introduces Lambda expressions and is considered to be the biggest new feature of Java 8. Lambda expressions promote functional programming, java programming is simplified.

Background Knowledge: anonymous internal class

In Java, anonymous internal classes are generally applicable to implementation classes that only appear once in Java applications. For example, in standard Swing or JavaFX applications, there are many keyboard and mouse event handlers. Generally, you do not need to write a separate event processing class, but use the following method (you should be familiar with Swing programming experience):

JButton testButton = new JButton ("Test Button");
        testButton.addActionListener (new ActionListener ()
        {
            @Override
            public void actionPerformed (ActionEvent ae)
            {
                System.out.println ("Click Detected by Anon Class");
            }
        });
If you do n’t do this, you need to write a separate implementation class of the ActionListener interface for each event. This code is not elegant, because you only need to write a lot of code to define a method. Usually, where necessary, create the corresponding anonymous inner class, such code will be more readable.

Functional Interfaces
First, let's observe the definition of the ActionListener interface mentioned above, as follows:

package java.awt.event;

import java.util.EventListener;


public interface ActionListener extends EventListener {

    / **
     * Invoked when an action occurs.
     * /
    public void actionPerformed (ActionEvent e);

}
In the above code, only one method is defined. In Java 8, an interface like this is called a "functional interface". Usually in Java, we often use anonymous inner classes to implement functional interfaces, which is a very common usage pattern;

In addition, in the JDK, in addition to the ActionListener interface, there are similar Runnable and Comparator interfaces.

Lambda expression syntax
The syntax of Lambda expression is as follows:

parameter-> expression body
Main components: parameter list + arrow + expression body, such as (int x, int y)-> x + y

Among them, the expression body can be an expression or a statement block (multiple code statements);

Lambda expressions have the following characteristics:

[Optional] Type declaration: the type of the parameter does not need to be declared, the compiler can infer its type based on the parameter value;
[Optional] Brackets: For a single parameter, there is no need to surround the parameters with parentheses. Of course, for multiple parameters or no parameters, the brackets are required;
[Optional] Braces: If there is only one statement in the expression body, there is no need to surround it with curly braces. Of course, for multiple statements, curly braces are required;
[Optional] return keyword: if the expression body is a single expression, the return keyword can not be written, the compiler can automatically return the value, of course, if you write return, you need to add curly braces;
for example:

package lambda;

/ **
 * LambdaTest
 *
 * @author Pi Chen
 * @version V1.0.0, September 19, 2016
 * @see
 * @since V1.0.0
 * /
public class LambdaTest
{
    public static void main (String args [])
    {
        LambdaTest tester = new LambdaTest ();

        // There are parameter types
        MathOperation addition = (int a, int b)-> a + b;

        // No parameter type
        MathOperation subtraction = (a, b)-> a-b;

        // There are curly braces and return keywords
        MathOperation multiplication = (int a, int b)-> {
            return a * b;
        };

        // No curly brackets, no return keywords, single expression
        MathOperation division = (int a, int b)-> a / b;

        // MathOperation call example
        System.out.println ("10 + 5 =" + tester.operate (10, 5, addition));
        System.out.println ("10-5 =" + tester.operate (10, 5, subtraction));
        System.out.println ("10 x 5 =" + tester.operate (10, 5, multiplication));
        System.out.println ("10/5 =" + tester.operate (10, 5, division));

        // with brackets
        GreetingService greetService1 = message-> System.out.println ("Hello" + message);

        // No parentheses, single parameter
        GreetingService greetService2 = (message)-> System.out.println ("Hello" + message);

        // Example of GreetingService call
        greetService1.sayMessage ("Mahesh");
        greetService2.sayMessage ("Suresh");
        
        // With brackets, without parameters
        Runnable runTest = ()-> System.out.println ("Running");
        // Runnable call example
        runTest.run ();
    }

    // Internal interface
    interface MathOperation
    {
        int operation (int a, int b);
    }

    interface GreetingService
    {
        void sayMessage (String message);
    }

    interface Runnable
    {
        void run ();
    }
    
    private int operate (int a, int b, MathOperation mathOperation)
    {
        return mathOperation.operation (a, b);
    }
}
Key points:

Lambda expressions are mainly used to define an inline implementation of a functional interface (functional interface: an interface containing only one method). In the above example, we used various types of Lambda expressions to implement the operation of the MathOperation interface Method, and then implemented the sayMessage method of the GreetingService interface and the run method of the Runnable interface;
Lambda expressions eliminate the use of anonymous classes and give Java simple and powerful functional programming capabilities;
References
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html#overview

https://www.tutorialspoint.com/java8/java8_lambda_expressions.htm

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.