Java 8 lambda expression Adventure

Source: Internet
Author: User
Tags new set

Why?
Why do we need lambda expressions
There are three main reasons:
> more Compact Code
For example, the existing anonymous inner classes in Java, as well as listeners (listeners) and event handlers (handlers), are very lengthy
> Ability to modify methods (I personally understand code injection, or a bit like JavaScript that passes a callback function to another function)
For example, the contains method of the collection interface returns True if and only if the passed-in element is really contained in the collection. And if we want to set a string, pass in a string, and return True if the string appears in the collection (ignoring the case).
Simply put, what we want is to pass in "some of our own code" into the existing method, and the existing method will execute the code we passed in. Lambda expressions can support this very well,
> Better support for multicore processing
For example, with the addition of a lambda expression in Java 8, we can easily manipulate large collections in parallel, giving full play to the potential of multi-core CPUs.
Parallel processing functions such as filter, map, and reduce.

What do you do?
Example 1 FileFilter

New File ("/an/dir/");   new FileFilter () {      booleanreturn file.isdirectory ();}};     

This code can be simplified as follows with a lambda expression:

New File ("/an/dir/"); FileFilter Directoryfilter = (File f), f.isdirectory (); file[] dirs = Dir.listfiles (directoryfilter); 

Further simplification:

New File ("/an/dir/"); file[] dirs = Dir.listfiles ((File f), F.isdirectory ());


Lambda expressions make code more readable. I admit that I was troubled by the anonymous inner class when I started to learn Java, and now the lambda expression makes it all look natural (especially with the. NET background of children's shoes, which looks like a lambda expression in. net)
Lambda expressions take advantage of type inference (inference) technology:

The compiler knows that FileFilter has only one method accept (), so the accept () method must correspond (File f), F.isdirectory ()
and the Accept () method has only one parameter of type file, so file F (file f), f.isdirectory () is this parameter,
. NET makes the type inference even more absolute, if the above is written in a. NET lambda expression:   file[] dirs = dir. Listfiles (f = f.isdirectory ()); That is, there is no need for file type indication at all. 

Example 2 Event Handler

New Button ();   Bt.addactionlistener (new ActionListener () {      void actionperformed (ActionEvent e) { Ui.showsomething (); }});


After using a lambda expression:

New Button (); ActionListener listener = event, {ui.showsomething ();}; Bt.addactionlistener (listener); 

Further simplification:

New Button (); Bt.addactionlistener (event, {ui.showsomething ();});

Outer Loop, inner loop and map, Reduce, Filter
Until now, the standard practice of working with Java collections is to take an outer loop. Like what:

New arraylist<string>(); List.add ("Hello"); List.add ("World") ; for (int// Processing Item}      

There are also iterator loops, all of which are outer loops and are sequentially processed (sequential handling). Sequential attributes also often raise concurrentmodificationexception, as long as we try to modify the collection concurrently.
Lambda expressions provide an inner loop mechanism.
We may often face the following requirements in our work:

> filters out a set of non-conforming elements to get a new set > to make some conversion to each element in the collection, and to process the transformed collection > to count a property of the entire collection, such as the sum or average of the statistical collection element values 

These tasks are filter, map, and reduce, and their common features are:
You need to run a small segment of the same code for each element in the collection.
The traditional code to implement these tasks is tedious, and fortunately Java 8 provides a more concise solution to these tasks, or the use of lambda expressions, but also introduces a new class library java.util.functions, containing predicate, Mapper and block.
In Java 8, a predicate (predicate) is a method that evaluates to the value of a variable (evaluate) and returns TRUE or false.
such as the following:

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 simplification:

list<string> list = getmystrings (); List.filter (S-s.equalsignorecase (possible));

Lambda expression Syntax rules
The lambda expression syntax rules in Java 8 have not been fully determined so far.
But here's a brief introduction:
For the previous:

New File ("/an/dir/"); file[] dirs = Dir.listfiles ((File f), F.isdirectory ());

The Accept () method returns a Boolean value, which f.isdirectory () obviously has to be a Boolean value. It's simple.
And for:

New Button (); Bt.addactionlistener (event, {ui.showsomething ();});

The return type of the actionperformed () method is void, so special handling is required, i.e. in ui.showsomething (), with curly braces around the left and right. (Imagine what it would be like not to add.) If not added, if the showsomething () method return value is an integer type, then it means that actionperformed () returns an integer type, which is obviously not, so the curly braces must be used to mark it.
If the body part of the lambda expression contains multiple statements, you must also use curly braces, and the return statement cannot be saved.
For example, the following:

New File ("/an/dir/"); file[] dirs = Dir.listfiles ((File f),  {                                             System.out.println ("Log: ...");                                            return f.isdirectory ();});    

Reference from: Http://www.oraclejavamagazine-digital.com/javamagazine/20121112?sub_id=hlBuL1SAFxXX#pg35

Java 8 lambda expression Adventure

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.