Java8 What is the use of a new attribute lambda expression (usage instance) _java

Source: Internet
Author: User
Tags anonymous getstream stream api

We've been looking for a long time for lambda to bring closure to Java, but we lose a lot of value if we don't use it in the collection. The problem of migrating existing interfaces into lambda style has been resolved through default methods, which will delve into the bulk data operations (bulk operation) In the Java collection, unlocking the mysteries of the most powerful of the lambda.

1. About JSR335

The JSR is the acronym for Java specification requests, meaning Java specification requests, and the main improvement in the Java 8 version is the LAMBDA project (JSR 335), which is designed to make Java easier to write code for multi-core processors. JSR 335=LAMBDA expression + interface Improvement (default method) + bulk data operation. Plus the first two, we have learned the full JSR335 of the relevant content.

2. External vs Internal Iterations

The previous Java collection was not able to express internal iterations, but provided only one way of external iteration, that is, for or while loops.

Copy Code code as follows:

List persons = aslist (new person ("Joe"), the new person ("Jim"), the new person ("John");
for (person P:persons) {
P.setlastname ("Doe");
}

The above example is our previous practice, that is, the so-called external iterations, the loop is a fixed sequential loop. In the current multi-core era, if we want to cycle in parallel, we have to modify the above code. How much efficiency can be increased is also agreed, and poses a certain risk (thread safety issues, etc.).

To describe an internal iteration, we need to use a class library such as Lambda, using lambda and collection.foreach to rewrite the loop above

Copy Code code as follows:
Persons.foreach (P->p.setlastname ("Doe"));

It is now up to the JDK library to control the loop, and we don't need to worry about how last name is set to each person object, and the library can decide what to do, parallel, disorderly, or lazy loading, depending on the context in which it is run. This is the internal iteration, where the client p.setlastname behavior as the data-passing API.

The internal iterations are not closely related to the bulk operation of the set, and we feel the changes in the grammatical expression. What's really interesting about bulk operations is the new stream API. The new Java.util.stream package has been added to JDK 8.

3.Stream API

Flow (stream) only represents the data flow, and there is no data structure, so he went through once again can not traverse (this point in the programming need to pay attention, not like collection, traverse how many times there are data), its source can be collection, array, Io and so on.

3.1 Intermediate and Endpoint methods

Flow action is to provide a large data interface to operate, make the data operation easier and faster. It has the methods of filtering, mapping and reducing the enumeration, these methods are divided into two types: the intermediate method and the terminal method, the "stream" abstraction is inherently persistent, the intermediate method always returns the stream, so if we want to obtain the final result, we must use the endpoint operation to collect the final result of the stream. The distinction between these two methods is to see his return value, if the stream is the intermediate method, otherwise is the endpoint method. Please refer to the stream's API for details.

Briefly introduce the next few intermediate methods (filter, map) and endpoint methods (collect, SUM)

3.1.1Filter

Filtering in the data stream is the most natural operation we can think of in the first place. The stream interface exposes a filter method that can accept the predicate implementation of a representation operation to use a lambda expression that defines a filter condition.

Copy Code code as follows:

List persons = ...
Stream personsOver18 = Persons.stream (). Filter (P-> p.getage () > 18);/filtration of people over 18 years of age

3.1.2Map

If we filter some data now, like converting objects. The map operation allows us to perform an implementation of a Function (the function<t,r> generic t,r represents the execution of input and execution results, respectively), and it accepts incoming parameters and returns. First, let's look at how to describe it in terms of anonymous inner classes:

Copy Code code as follows:

Stream adult= Persons
. Stream ()
. Filter (P-> p.getage () > 18)
. Map (New Function () {
@Override
Public adult apply (person person) {
Return to new Adult (person)//to adults older than 18 years
}
});

Now, convert the example above to the expression using lambda expressions:

Copy Code code as follows:

Stream map = Persons.stream ()
. Filter (P-> p.getage () > 18)
. Map (person-> new adult);

3.1.3Count

The Count method is the endpoint method of a stream that causes the result of the stream to be finally counted, returning int, for example, we calculate the total number of people who meet the age of 18:

Copy Code code as follows:

int Countofadult=persons.stream ()
. Filter (P-> p.getage () > 18)
. Map (person-> new adult)
. Count ();

3.1.4Collect

The Collect method is also a flow endpoint method that collects the final results

Copy Code code as follows:

List adultlist= Persons.stream ()
. Filter (P-> p.getage () > 18)
. Map (person-> new adult)
. Collect (Collectors.tolist ());

Or, if we want to use a specific implementation class to collect the results:

Copy Code code as follows:

List adultlist = Persons
. Stream ()
. Filter (P-> p.getage () > 18)
. Map (person-> new adult)
. Collect (Collectors.tocollection (arraylist::new));

Space is limited, the other intermediate methods and endpoint methods are not introduced, read the above several examples, we understand the difference between the two methods can be based on the need to decide to use.

3.2 Sequential flow and parallel flow

Each stream has two modes: sequential execution and parallel execution.
Sequential flow:

Copy Code code as follows:

List <Person> people = List.getStream.collect (Collectors.tolist ());

Parallel streams:
Copy Code code as follows:

List <Person> people = List.getStream.parallel (). Collect (Collectors.tolist ());

As the name suggests, when you use the sequential way to traverse, each item is read and then read the next item. When used in parallel to traverse, the array is divided into segments, each of which is processed in a different thread, and the result is output together.

3.2.1 Parallel Flow principle:

Copy Code code as follows:

List originallist = Somedata;
split1 = originallist (0, mid);//Divide the data into small portions
Split2 = Originallist (mid,end);
New Runnable (Split1.process ());//small number of actions performed
New Runnable (Split2.process ());
List revisedlist = split1 + split2;//Merge Results

Comparison between 3.2.2 Order and parallel performance test

In the case of multi-core machines, the theoretical parallel flow will be one times faster than the sequential flow, and the following is the test code

Copy Code code as follows:

Long T0 = System.nanotime ();

Initializes a range of 1 million integer streams, seeking numbers that are divisible by 2, ToArray () is the endpoint method

int A[]=intstream.range (0, 1_000_000). Filter (P-> p% 2==0). ToArray ();

Long T1 = System.nanotime ();

As with the above function, here is a parallel flow to compute

int B[]=intstream.range (0, 1_000_000). Parallel (). Filter (P-> p% 2==0). ToArray ();

Long t2 = System.nanotime ();

The result of my native is serial:0.06s, parallel 0.02s, which proves that parallel flow is indeed faster than sequential flow

System.out.printf ("Serial:%.2FS, Parallel%.2fs%n", (t1-t0) * 1e-9, (T2-T1) * 1e-9);

3.3 about the Folk/join framework

Application hardware parallelism in Java 7, that is, one of the new features of the Java.util.concurrent package is a fork-join style of parallel decomposition framework, but also very powerful and efficient, interested students to study, here is unknown talk, I am more inclined to the latter than the Stream.parallel () approach.

4. Summary

If no lambda,stream is awkward to use, he will produce a large number of anonymous internal classes, such as the above 3.1.2map example, if there is no default method, the collection frame changes are bound to cause a lot of changes, so Lambda+default Method makes the JDK library more powerful and flexible, and the improvement of the stream and the set framework is the best proof.

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.