Java Reference
In-Depth Information
result in a data structure that forms the final output of this process. For instance, in our
transaction-grouping example shown previously, the transformation function extracts the
currency from each transaction, and subsequently the transaction itself is accumulated in the
resulting Map, using the currency as key.
The implementation of the methods of the Collector interface defines how to perform a
reduction operation on a stream, such as the one in our currency example. We investigate how
to create customized collectors in sections 6.5 and 6.6 . But the Collectors utility class provides
lots of static factory methods to conveniently create an instance of the most common collectors
that are ready to use. The most straightforward and frequently used collector is the toList static
method, which gathers all the elements of a stream into a List:
List<Transaction> transactions =
transactionStream.collect(Collectors.toList());
6.1.2. Predefined collectors
In the rest of this chapter, we mainly explore the features of the predefined collectors, those that
can be created from the factory methods (such as groupingBy) provided by the Collectors class.
These offer three main functionalities:
Reducing and summarizing stream elements to a single value
Grouping elements
Partitioning elements
We start with collectors that allow you to reduce and summarize. These are handy in a variety of
use cases such as finding the total amount of the transacted values in the list of transactions in
the previous example.
You'll then see how to group the elements of a stream, generalizing the previous example to
multiple levels of grouping or combining different collectors to apply further reduction
operations on each of the resulting subgroups. We'll also describe partitioning as a special case
of grouping, using a predicate, a one-argument function returning a boolean, as a grouping
function.
At the end of section 6.4 you'll find a table summarizing all the predefined collectors explored in
this chapter. Finally, in section 6.5 you'll learn more about the Collector interface before you
explore ( section 6.6 ) how you can create your own custom collectors to be used in the cases not
covered by the factory methods of the Collectors class.
 
Search WWH ::




Custom Search