Java: Aggregation Operations (2)

Source: Internet
Author: User
Tags function prototype

Unlike the reduce operation, a new value is generated for each element that is processed, and the Collect method only updates the existing value.

Or assuming the average weight of the backpack is required, what values do you need? Total weight and total number. You can create a new data type that contains and tracks these two variables.


Class Averager implements intconsumer{    private int total = 0;    private int count = 0;            Public double average () {        return count > 0? ((double) total)/count:0;    }            public void Accept (Int. i) {total + = i; count++;}    public void Combine (Averager other) {total        + = Other.total;        Count + = Other.count;    }}

The Intcousumer interface accepts a parameter of type int and does not return any values. Averager's accept is rewritten.


Here's how the pipeline uses Averager and collect to do the averaging.

Averager average =         packages.stream ()         . Map (package::getweight)         . Collect (Averager::new,         Averager:: Accept,averager::combine)

The function reference is used here, and no lambda expression is used. Note that the container for the collect operation must be mutable.

First look at the function prototype of collect,

<R> R Collect (supplier<r> Supplier,             biconsumer<r,? Super t> Accumulator,             biconsumer<r,r > Combine)

The first parameter, supplier, represents the assembly type of the result set. The Biconsumer accepts two parameters and does not return the result of the operation.

The second parameter and the third parameter are all "associative", "stateless", "non-intrusive". "Adding an element to the result", "combining two results (which is a merger process)".

The previous article on "bonding" has been explained. Here is a description of the latter two properties.


A stateful lambda expression means that its result depends on any state that might change in the execution of the pipeline. This statement is a bit of a mouthful, its English words are:

A stateful Lambda is one whose result depends on any state which might change during the execution of the stream pipeline

The following function in map is stateful,

Set<integer> seen = Collections.synchronizedset (new hashset<> ());     Stream.parallel (). Map (E, {if (Seen.add (e)) return 0; else return e;}) ...

For the same input, the results may be different for multi-threaded concurrency operations.


Stream operations allow you to perform parallel computations, even for non-thread-safe collections such as ArrayList. This requires us to prevent interference from the data source. For most data sources, preventing interference means making sure that the pipe operation cannot be modified. One exception is when the data source is a parallel collection. Note that "non-interference" is required for all pipelines, not just for parallel computing. In addition to being a parallel collection (current Collection), modifying the data source at execution time can result in an exception or an incorrect result. For a well-behaved stream, changes to the data source should be reflected in the elements involved.


list<string> L = new ArrayList (Arrays.aslist ("One", "one");     stream<string> SL = L.stream ();     L.add ("three");     String s = sl.collect (Joining (""));


We are going to modify the L, and the last SL will still change, as long as this modification occurs before the end operation.


It is equivalent to,

R result = Supplier.get ();     For (T element:this stream)         accumulator.accept (result, element);     return result;


One more example, complete string concatenation,

String concat = Stringstream.collect (Stringbuilder::new, Stringbuilder::append,                                          stringbuilder::append)                                 . ToString ();


The collect operation is best suited for collection operations. The following is the weight of all the backpacks into a list<integer> collection,

List<integer> weights = Packages.stream ()             . Maptoint (P-p.getweight ())             . Collect (Collectors.tolist ());

This version of Collect has only one parameter collector, which encapsulates the supplier,accumulator and combine required by collect.

Collectors contains many useful reduction operations, and all return collector.

The ToList method above accumulates the elements of the stream into a new list instance.

Suppose the backpack is colored, has a color attribute, and has a setter and getter. We classify them by color:

Map<string color,list<package> Bycolor   = Packages.stream ()    . Collect (         Collectors.groupingby ( Person::getcolor)    );



Java: Aggregation Operations (2)

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.