Java lambda expression

Source: Internet
Author: User

A lambda expression is an anonymous function, which is a common explanation: a block of code that can be passed and executed one or more times at a later time. The features introduced in the JAVA8.

The syntax of a lambda expression

Form: (parameter)--expression

0. If the expression is complex, it can be enclosed in curly braces. {Statement block}

1. Without parameters: An empty parenthesis is still required.

()->{ for (int i = 100;i >= 0;i--) System.out.println (i);}

2. If you can push the export parameter type: You can omit the parameter type.

Compertor<string> comp = (first,second)->first.length ()-scond.length ();//parameter type must be string

3. If there is only one parameter, you can push the export parameter type: You can omit the parentheses.

4. You do not need to specify the return type of the lambda expression, which is automatically inferred from the context.

Function-Type interface

For an interface that has only one abstract method, you can provide a lambda expression when an object of this interface is required. An interface with only one abstract method is called a functional interface.

The Array.Sort method needs to provide an array and a comparer (comparator). The comparer is an instance object that implements the comparator interface. There is only one method for this interface. As common implementations:

class Implements Comparator<string>{    publicint  Compare (String first,string second) {         return first.length ()- second.length ();}    }

In this way, you can create a Lengthcomparater class into the Array.Sort function.

Array.Sort (words,new lengthcomparator ())

Instead, use a lambda expression:

Array.Sort (words, (first,second)->first.length ()-secong.length ())

In doing so, the call to the Compare method executes the body of the lambda expression, which considers lambda a function. This is more efficient, and the code is much more readable.

Method reference

use a double colon (::) to separate methods and object names to represent a method reference , as with a lambda expression. There are 3 ways to do this:

Object::instancemethod (X,x,x ...) Equivalent to (x,x,x ...) ->object.instancemethod (X,x,x ...)

Class::staticmethod (x,x,x,....) Equivalent to (x,x,x ...) ->object.staticmethod (X,x,x ...)

Class::instancemethod (x, Y, Z ...)  Equivalent to (x)->x.instancemethod (Y,z ...) The first parameter becomes the target of the method

You can use this and the super parameter in a method reference

Constructor reference

Similar to the method reference, the method name is new. For example, Person::new is a reference to the person constructor.

Variable scope

Lambda expressions can capture the values of variables in the perimeter scope, but there are some limitations.

Rule:A variable captured in a lambda expression must actually be the final variable.

An example:

     Public Static void int count)  {        for (int i = 1;i <= count; i++) {            = event,{                + "" +  text);            };             New Timer (10000, LS). Start ();        }    }

As above, for the text of the printing is legal, the printing of I is illegal. Text always points to the same object, while the value of I changes.

Rule:the body of a lambda expression has the same scope as a nested block.

An example:

    Path first = Paths.get ("Usr/bin");    Comparator<String> comb = (first,second) first.length ()-second.length ();

The above is illegal. There cannot be two local variables with the same name in a method. Therefore, the above lambda expression cannot use the first variable name as a parameter.

Working with lambda expressions

Simple example: Repeat an action n times, using the repeat method.

Repeat (System.out.println ("Hello World");

A functional interface needs to be implemented, where the Runnable interface is used, and the function body is executed when calling Action.run ():

 Public Static void repeat (int  n,runnable action) {    for (int i;i<n;i++) Action.run ();}

What a lambda expression can actually do is convert it into a functional interface.

Some common functional interfaces: Runnable,supplier,consumer,biconsumer,function,bifunction,unaryoperator,binaryoperator,predicate, Bipredicate.

Java lambda expression

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.