Java Reference
In-Depth Information
The following snippet of code uses the
map()
and
reduce()
methods to implement the count operation:
long personCount = Person.persons()
.stream()
.map(p -> 1L)
.reduce(0L, Long::sum);
The following snippet of code uses only the
reduce()
method to implement the count operation:
long personCount = Person.persons()
.stream()
.reduce(0L, (partialCount, person) -> partialCount + 1L, Long::sum);
■
this section showed you many ways to perform the same reduction operation on a stream. Some ways may
perform better than others depending on the stream type and the parallelization used. Use primitive type streams
whenever possible to avoid the overhead of unboxing; use parallel streams whenever possible to take advantage of the
multicores available on the machine.
Tip
Collecting Data Using Collectors
So far, you have been applying reduction on a stream to produce a single value (a primitive value or a reference
value) or
void
. For example, you used the
reduce()
method of the
Stream<Integer>
interface to compute a
long
value that is the sum of its elements. There are several cases in which you want to collect the results of executing a
stream pipeline into a collection such as a
List
, a
Set
, a
Map
, etc. Sometimes you may want to apply complex logic to
summarize the stream's data. For example, you may want to group people by their gender and compute the highest
earner in every gender group. This is possible using the
collect()
method of the
Stream<T>
interface. The
collect()
method is overloaded with two versions:
<R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator,
BiConsumer<R,R> combiner)
•
<R,A> R collect(Collector<? super T,A,R> collector)
The method uses a mutable reduction operation. It uses a mutable container such as a mutable
Collection
to
compute the results from the input stream. The first version of the
collect()
method takes three arguments:
•
•
supplier
that supplies a mutable container to store (or collect) the results.
A
•
An
accumulator
that accumulates the results into the mutable container.
•
combiner
that combines the partial results when the reduction operation takes
place in parallel.
A
■
the container to collect the data using the
collect()
method need not be a
Collection
. It can be any mutable
object that can accumulate results, such as a
StringBuilder
.
Tip