Explore the Java language and lambda expressions in the JVM

Source: Internet
Author: User
Tags compact java se

Lambda expression is the most significant new Java language feature since Java SE 5 introduced generics, this article is an article in the last issue of Java Magazine in 2012, which introduces LAMDBA's design intent, application scenarios, and basic syntax. (Last updated 2013.01.02)

The lambda expression, chosen by the Expert group of the project, describes a new functional programming structure that is eagerly awaited by the new features that will appear in Java SE 8. Sometimes you will also hear the use of terms such as closures, function direct amounts, anonymous functions, and Sam (Single Abstract Method). Some of these terms are slightly different from each other, but basically they all refer to the same functionality.

Although the lambda expression looks strange at first, it is easy to master. And in order to write applications that can take full advantage of modern multicore CPUs, mastering lambda expressions is critical. Front-end UI framework sharing

A key concept to keep in mind is that a lambda expression is a small function that can be passed as data. The second concept that needs to be mastered is to understand how the collection object is traversed internally, which is different from the currently existing external sequential traversal.

In this article, we'll show you the motivations behind the lambda expression, the application example, and, of course, its syntax.

Why do you need a lambda expression

There are three main reasons programmers need lambda expressions:

1. More compact Code

2. Ability to modify the functionality of the method by providing additional functionality

3. Better support for multicore processing

More compact Code

Lambda expressions implement a Java class that has only one method in a concise way.

For example, if you have a large number of anonymous inner classes in your code – such as listeners and processor implementations for UI applications, and callable and runnable implementations in concurrent applications – after using lambda expressions, the code becomes very short and easier to understand.

Ability to modify methods

Sometimes the method does not have some of the features we want. For example, the contains () method in the collection interface returns true only if the incoming object does exist in the collection object. But we cannot intervene in the function of this method, for example, if a different casing scheme can be used to think that the string being looked up exists in this collection object, we hope that the contains () method will return true at this point.

To put it simply, what we'd like to do is "pass our own new code into" the existing method, and then call the code passed in. Lambda expressions provide a good way to represent the code that is passed into an existing method and should also be recalled.

Better support for multicore processing

Today's CPUs have multiple cores. This means that multithreaded routines can really be executed in parallel, which is completely different from using time sharing in a single-core CPU. By supporting functional programming syntax in Java, lambda expressions can help you write simple code to effectively apply these CPU cores.
For example, you can manipulate large collection objects in parallel, using parallel programming patterns, such as filtering, mapping, and simplifying (which will soon be exposed to these patterns), to use all available hardware threads in the CPU.

Lambda expression Overview

In the previous example of finding a string using a different casing scheme, what we want to do is to pass the representation of the method toLowerCase () as the second parameter into the contains () method, which requires the following work:

1. Find a way to treat code snippets as a value (an object)

2. Find a way to pass the code snippet above to a variable

In other words, we need to wrap a program logic into an object, and the object can be passed. To be more specific, let's look at two examples of basic lambda expressions that can be replaced by existing Java code. Front-end UI framework sharing

Filter

The code snippet you might want to pass may be a filter, which is a good example. For example, suppose you are using Java.io.FileFilter (in Java SE 7 preview) to determine whether a directory is subordinate to a given path, as shown in Listing 1,

Listing 1

1234567 File dir = newFile("/an/interesting/location/");FileFilter directoryFilter = newFileFilter() {        publicbooleanaccept(File file) {        returnfile.isDirectory();    }};File[] directories = dir.listFiles(directoryFilter);

After using a lambda expression, the code is greatly simplified, as shown in Listing 2.

Listing 2

123 File dir = newFile("/an/interesting/location/");FileFilter directoryFilter = (File f) -> f.isDirectory();File[] directories = dir.listFiles(directoryFilter);

The left side of the assignment expression infers the type (FileFilter), and the right side looks like a smaller version of the Accept () method in the FileFilter interface, which accepts a file object and returns a Boolean value after the decision F.isdirectory ().

In fact, because lambda expressions take advantage of type derivation, we can further simplify the code above, based on how it works later. The compiler knows that FileFilter has only the only method accept (), so it must be the implementation of the method. We also know that the accept () method requires only one parameter of type file. Therefore, F must be of type file. As shown in Listing 3,

Listing 3

12 File dir = newFile("/an/interesting/location/");File[] directories = dir.listFiles(f -> f.isDirectory());

As you can see, using lambda expressions can drastically reduce the number of template code.

Once you get used to using lambda expressions, it makes the logic flow very easy to read. One of the key ways to achieve this is to place the filtering logic on the side of the method that uses the logic.

Event handlers

A UI program is another area where anonymous internal classes are heavily used. Let's assign a click Listener to a button, as shown in Listing 4,

Listing 4

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.