Java 8 Lambda expression Exploration

Source: Internet
Author: User

Why?
Why do we need lambda expressions?
There are three main reasons:
> More compact code
For example, the existing anonymous internal classes in Java, as well as listeners and handlers are all very lengthy.
> Ability to modify methods (I personally think it is code injection, or a bit similar to a callback function in JavaScript to another function)
For example, the contains method of the collection interface returns true only when the input elements are actually included in the collection. If we want to input a string to a string set, as long as the string appears in the Set (case-insensitive), true is returned.
To put it simply, we want to pass in "some of our own code" to an existing method, and the existing method will execute the passed-in code. Lambda expressions support this well.
> Better support for multi-core processing
For example, through the lambda expressions added in Java 8, we can easily operate large sets of parallel operations and make full use of the potential of multi-core CPUs.
Parallel processing functions such as filter, map, and reduce.

 

How?
Instance 1 filefilter

File dir = new File("/an/dir/");   FileFilter directoryFilter = new FileFilter() {      public boolean accept(File file) {         return file.isDirectory();      }};

The code using lambda expressions can be simplified as follows:

File dir = new File("/an/dir/");FileFilter directoryFilter = (File f) -> f.isDirectory();File[] dirs = dir.listFiles(directoryFilter);

Further simplified:

File dir = new File("/an/dir/");File[] dirs = dir.listFiles((File f) -> f.isDirectory());

Lambda expressions enhance code readability. I admit that I was troubled by the anonymous internal class when I started learning Java, and now lambda expressions make it all look natural (especially when there is.. Net background.. Net lambda expressions)


Lambda expressions use the type inference technology:

The compiler knows that filefilter has only one accept () method, so the accept () method must correspond to (file F)-> F. isdirectory ()
The accept () method has only one file type parameter, so file F in (file F)-> F. isdirectory () is the parameter,
. Net to make the type inference more absolute, if the above uses. net lambda expressions are written as follows: file [] dirs = dir. listfiles (F => F. isdirectory (); that is, there is no need to indicate the file type.

Instance 2 event handler

Button bt = new Button();   bt.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent e) {         ui.showSomething();      }});

After lambda expressions are used:

Button bt = new Button();ActionListener listener = event -> { ui.showSomething(); };bt.addActionListener(listener);

Further simplified:

Button bt = new Button();bt.addActionListener(event -> { ui.showSomething(); });

 

External Loop, internal loop, MAP, reduce, filter
Until now, the standard practice for processing Java sets is to use external loops. For example:

List <string> List = new arraylist <string> (); list. add ("hello"); list. add ("world"); For (INT item: List) {// process item}

There are also iterator loops, which are both external loops and sequential processing (sequential handling ). The Order feature often triggers concurrentmodificationexception, as long as we try to modify the set concurrently.
Lambda expressions provide an internal loop mechanism.


We may often face the following requirements in our work:

> Filter out non-conforming elements in a set to get a new set> convert each element in the set, process the converted set> calculate an attribute of the entire set, such as the sum or average of the element values of the set.

These tasks are filter, map, and reduce tasks. They share the following features:
You need to run a short piece of the same code for each element in the set.


The traditional code for implementing these tasks is boring. Fortunately, Java 8 provides a more concise solution for completing these tasks. Of course, it still uses lambda expressions, however, a new class library Java. util. functions, including predicate, Mapper, and block.


In Java 8, a predicate (predicate) is such a method: It evaluates (evaluate) based on the value of the variable and returns true or false.


For example:

List<String> list = getMyStrings();for(String myString: list) {   if(myString.contains(possible)) {       System.out.println(myString + " contains " + possible);   }}

Use predicate and filter to get the following code:

List<String> list = getMyStrings();Predicate<String> matched = s -> s.equalsIgnoreCase(possible);list.filter(matched);

Further simplified:

List<String> list = getMyStrings();list.filter(s -> s.equalsIgnoreCase(possible));

 

Lambda expression syntax rules
So far, the lambda expression syntax rules in Java 8 have not been completely determined.

But here is a brief introduction:

For the preceding:

File dir = new File("/an/dir/");File[] dirs = dir.listFiles((File f) -> f.isDirectory());

The accept () method returns a Boolean value. In this case, F. isdirectory () must also be a Boolean value. This is simple.
For:

Button bt = new Button();bt.addActionListener(event -> { ui.showSomething(); });

The return type of the actionreceivmed () method is void, so special processing is required, that is, brackets are added to the left and right sides of UI. showsomething. (Imagine what if I don't add it? If no value is added, if the return value of the showsomething () method is of the integer type, it means that actionreceivmed () returns the integer type, obviously not, so curly brackets must be added for marking ).
If the body of a Lambda expression contains multiple statements, brackets must be used, and the return statement cannot be saved.


For example:

File dir = new File("/an/dir/");File[] dirs = dir.listFiles((File f) ->  {                                             System.out.println("Log:...");                                            return f.isDirectory();                                          });

 

Reference: http://www.oraclejavamagazine-digital.com/javamagazine/20121112? Sub_id = hlbul1safxxx # pg35

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.