Java Reference
In-Depth Information
Chapter 6. Collecting data with streams
This chapter covers
Creating and using a collector with the
Collectors
class
Reducing streams of data to a single value
Summarization as a special case of reduction
Grouping and partitioning data
Developing your own custom collectors
You learned in the previous chapter that streams help you process collections with database-like
operations. You can view Java 8 streams as fancy lazy iterators of sets of data. They support two
types of operations: intermediate operations such as filter or map and terminal operations such
as count, findFirst, forEach, and reduce. Intermediate operations can be chained to convert a
stream into another stream. These operations don't consume from a stream; their purpose is to
set up a pipeline of streams. By contrast, terminal operations
do
consume from a stream—to
produce a final result (for example, returning the largest element in a stream). They can often
shorten computations by optimizing the pipeline of a stream.
We already used the collect terminal operation on streams in
chapters 4
and
5
, but we employed
it there mainly to combine all the elements of a Stream into a List. In this chapter, you'll
discover that collect is a reduction operation, just like reduce, that takes as argument various
recipes for accumulating the elements of a stream into a summary result. These recipes are
defined by a new Collector interface, so it's important to distinguish Collection, Collector, and
collect!
Here are some example queries of what you'll be able to do using collect and collectors:
Group a list of transactions by currency to obtain the sum of the values of all transactions with that
currency (returning a
Map<Currency, Integer>
)
Partition a list of transactions into two groups: expensive and not expensive (returning a
Map<Boolean, List<Transaction>>
)
Create multilevel groupings such as grouping transactions by cities and then further categorizing by
a
Map<String
,
Map<Boolean
,
whether
they're
expensive
or
not
(returning
List<Transaction>>>
)
Excited? Great, let's start by exploring an example that benefits from collectors. Imagine a
scenario where you have a List of Transactions, and you want to group them based on their
Search WWH ::
Custom Search