Lambda expressions in Java 8

Source: Internet
Author: User

Java 8 is expected to be released in 2013, and Java 8 will support the Lambda function. Although the specification is still changing, the development version of Java 8 has implemented support for lambda.

For the definition of lambda expressions, see Wikipedia.

This article will familiarize you with the lambda syntax and use lambda in the collection API and related language enhancements. All the code in this article is compiled in JDK 8 lambda build b39.

Function Interface

An interface that contains only one method is called a functional interface, and a Lambda expression is used for any functional interface.

Java. awt. event. ActionListener is a functional interface, because it has only one method: void actionreceivmed (ActionEvent). In Java 7, we will write the following code:

12345 button. addActionListener (new ActionListener () {public void actionreceivmed (ActionEvent e) {ui. dazzle (e. getModifiers ());}});

Java 8 can be simplified:

1 button. addActionListener (e-> {ui. dazzle (e. getModifiers ());});

The compiler knows that the lambda expression must comply with the definition of the void actionreceivmed (ActionEvent) method. It seems that the lambda object returns void. In fact, it can infer that the type of parameter e is java. awt. event. ActionEvent.

Function set

The Java 8 class library contains a new package, java. util. functions. This package contains many new functional interfaces that can be used together with the collection API.

Java. util. functions. Predicate

Use Predicate to filter the set:

1234567 Listnames = Arrays. asList ("Alice", "Bob", "Charlie", "Dave"); List filteredNames = names. filter (e-> e. length ()> = 4 ). into (new ArrayList (); for (String name: filteredNames) {System. out. println (name );}

Here we have two new methods:

● Iterable <T> filter (Predicate <? Super T>) is used to obtain the result that an element meets a certain predicate and returns true.

● <A extends Fillable <? Super T> A into (A) will fill the ArrayList with the returned results

Java. util. functions. Block

We can use a new iterator method to replace the for loop void forEach (Block <? Super T> ):

1234 List <String> names = Arrays. asList ("Alice", "Bob", "Charlie", "Dave"); names. filter (e-> e. length ()> = 4 ). forEach (e-> {System. out. println (e );});

The forEach () method is an instance of internal iteration: the iteration process is performed within the Iterable and Block, and one element can be accessed each time.

The final result is to process the set with less code:

12345678 Listnames <String> = Arrays. asList ("Alice", "Bob", "Charlie", "Dave"); names. mapped (e-> {return e. length ();}). asIterable () // returns an Iterable of BiValue elements // an element's key is the person's name, its value is the string length. filter (e-> e. getValue ()> = 4 ). sorted (a, B)->. getValue ()-B. getValue ()). forEach (e-> {System. out. println (e. getKey () + '\ t' + e. getValue ());});

The advantages of doing so are:

The element is computed only when necessary.

If we take the first three of a set with thousands of elements, other elements will not be mapped.

Encourage method chain

We don't need to store intermediate results to build a new set.
Therefore, most details of the internal iteration process

For example, we can use the following code to perform parallel map () operations.

Writing myCollection. parallel (). map (e branch> e. length ()).

Method reference

We can reference a method using the: syntax. Method references are considered the same as lambda expressions and can be used in functional interfaces.

We can reference a static method:

1234 executorService. submit (MethodReference: sayHello); private static void sayHello () {System. out. println ("hello ");}

Or an instance method:

1 Arrays. asList ("Alice", "Bob", "Charlie", "Dave"). forEach (System. out: println );

You can also create a project method and assign the constructor reference to java. util. functions. Factory:

12 Factory biscuitFactory = Biscuit: new; Biscuit biscuit = biscuitFactory. make ();

Finally, we create an example to reference a random instance:

 

12345678 interface Accessor {PROPERTY access (BEAN bean);} public static void main (String [] args) {Address address = new Address ("29 Acacia Road ", "Tunbridge Wells"); Accessor accessor = Address: getCity; System. out. println (accessor. access (address ));}

Here we do not need to bind a method to reference an instance. We directly pass the instance as a parameter of the function interface.

Default Method

Until today, Java cannot add methods for an interface without affecting existing implementation classes. Java 8 allows you to specify a default implementation for the interface itself:

12345678910 interface Queue {Message read (); void delete (Message message); void deleteAll () default {Message message; while (message = read ())! = Null) {delete (message );}}}

The sub-interface can overwrite the default method:

1234567 interface BatchQueue extends Queue {void setBatchSize (int batchSize); void deleteAll () default {setBatchSize (100); Queue. super. deleteAll ();}}

Or the sub-interface can also delete the default method by declaring a method without a method body:

123 interface FastQueue extends Queue {void deleteAll ();}

This will force all classes that implement FastQueue to implement the deleteAll () method.

HotSpot implementation

Lambda not only reduces the writing of a lot of code, but also improves the efficiency of bytecode and runtime implementation than anonymous classes in Java 7. For each lambda expression, the compiler creates a method like lambda $1. This process is called lambda body desugaring. When a lambda expression is met, the compiler will initiate an invokedynamic call and obtain the return value from the target function interface.

Author: Sweet Potato

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.