Java8 Functional Programming-collector collector

Source: Internet
Author: User
Tags addall stream api

Java8 Stream API can be very convenient for us to statistical classification of data, etc., before we write a lot of statistical data code is often iterative, not to say that others do not understand, their code for a long time also need to look back a while to understand. Now, Java8 absorbs the new features of the language for scientific computing and provides the stream API, which makes it possible to write statistical code conveniently and intuitively.

There is a collect (Collector C) method in the stream that requires the interface to be passed into the Collector collector. Now let's talk about the responsibilities of this interface definition.

Public interface collector<t, A, r> {supplier<a> Supplier ();    Biconsumer<a, t> Accumulator ();    Binaryoperator<a> combiner ();    Function<a, r> finisher (); Set<characteristics> characteristics ();}

Collector mainly defines the type of container, the method of adding elements, the method of container merging and the result of output.


Supplier is the build container, accumulator is the add element, Combiner is the merge container, finisher is the result of the output,characteristics is the three attributes that define the container, including whether there is a definite finisher, Whether it needs to be synchronized or ordered.


For example:collectors has a tolist () method that returns a collector as follows

Collector (Arraylist::new,list::add,list::addall,identity_finish)

As you can see, first an instantiation of the ArrayList, then the add element using the list of Add methods, the container merge is the AddAll method. There is no finisher, because the end result is that List,finisher is the return container. But how does the Stream.collect () method know? is obtained by means of an enumeration type. Three enumeration types:

Identity_finish without Finisher,doc description for elided (can be omitted) UNORDERED collection is unordered concurrent the operation of the collection needs to be synchronized

Define the collector, and eventually the Collect method that passes into the stream, the end of the operation will be collected by the statistics you define and the collected operations. There is a collectors class in the JDK source code that has defined a lot of operations for us, and we simply add some of the collected definitions to work well for us.

Here the emphasis is on a Groupingby () method. If we had learned SQL statements, we would have learned that we would often use the GroupBy method. Now let's look at the source code to see how this approach is implemented. The final appearance of this method is the following

public static <t, K, D, A, M extends Map<k, d>> collector<t,?, m> Groupingby (function<? Super T, ?                                  Extends k> classifier, supplier<m> mapfactory, collector<? Super T, A, d> downstream)

When you are using the

Groupingby (E->e.getname ())

Actually called the

Groupingby (E->e.getname (), ToList ())

And finally called the

Groupingby (E->e.getname (), Hashmap::new,tolist ())

Which is the long lump above. What kind of collector does this groupingby method give us? Now let's analyze it.

For example, we know that the final result of the container is map, more accurate, is a hashmap. So

Supplier = Hashmap::new

Then is the Accmulator, first obtains the map key through the E->e.getname (), then generates or takes out the key corresponding value, then for ToList (), the value is the list, then adds the element in the list, can obtain

Accmulator = (Map,elemet), {1. Get key, 2. Get container from the map via key, no Container words instantiate a new container (by Downstream.supplier get list), 3. Executes the Downstream.accmulator method on container, which is the Add method}

The above downstream is the ToList method that gives us the return collector, which we call the downstream collector.

Then combiner also used the Downstream.combiner, but the container is a map that gets

Mapmerger (Downstream.combiner) is AddAll

Here you need to refer to map's default method Mapmerger method. The general meaning of this method is to traverse each key in the map.

private static <k, V, M extends map<k,v>> binaryoperator<m> mapmerger (binaryoperator<v> mergeFu Nction) {return (M1, M2), {for (map.entry<k,v> e:m2.entryset ()) M1.merge (E            . GetKey (), E.getvalue (), mergefunction);        return M1;    }; }

Finally, we can get a collector like this.

Collector (supplier = hashmap::new, Accmulator = {get key, get container, use downstream accmulator} combiner = Mapmerge R (Downstream.combiner))

Finisher and characteristics do not elaborate, because generally finisher can be omitted, when can not be omitted, is the downstream collector of the finisher, the source of the experience, need to understand clearly can be serious source.

Give one more example:

Collect (Groupingby (E->e.getartist (), Mapping (Artist->artist.getname ()))

Finally get the collector

collector (supplier = hashmap::new,           accmulator = {  get key, get container,                             use downstream accmulator.accept (Container,artist->artist.getname ())                          }          combiner =  Mapmerger (Downstream.combiner)          ) 

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------This is the happy dividing line-------------------------------------------------------- ----------------------------------------------------------------------------------------------------------


Summarize:

Collectors are powerful, and in general, the collectors inside the JDK comes with the usual requirements, and the inside of the collectors lets us know more about how to use it. While writing this blog post, my impression of collector also deepened, so suggest that you also write a blog, you will benefit a lot. Keep learning new features and add them to your code if you have the chance.

Hope this blog post can let you have lost a harvest!

Java8 Functional Programming-collector collector

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.