Java Reference
In-Depth Information
do that using the
toCollection
collector, which takes a function to build the collection as its
argument (see
Example 5-5
)
.
Example 5-5. Collecting into a custom collection using toCollection
stream
.
collect
(
toCollection
(
TreeSet:
:
new
new
));
To Values
It's also possible to collect into a single value using a collector. There are
maxBy
and
minBy
collectors that let you obtain a single value according to some ordering.
Example 5-6
shows
how to find the band with the most members. It defines a lambda expression that can map an
artist to the number of members. This is then used to define a comparator that is passed into
the
maxBy
collector.
Example 5-6. Finding the band with the most members
public
public
Optional
<
Artist
>
biggestGroup
(
Stream
<
Artist
>
artists
) {
Function
<
Artist
,
Long
>
getCount
=
artist
->
artist
.
getMembers
().
count
();
return
return
artists
.
collect
(
maxBy
(
comparing
(
getCount
)));
}
There's also a
minBy
, which does what it says on the tin.
There are also collectors that implement common numerical operations. Let's take a look at
these by writing a collector to find the average number of tracks on an album, as in
Example 5-7. Finding the average number of tracks for a list of albums
public
public
double
double
averageNumberOfTracks
(
List
<
Album
>
albums
) {
return
return
albums
.
stream
()
.
collect
(
averagingInt
(
album
->
album
.
getTrackList
().
size
()));
}
As usual, we kick off our pipeline with the
stream
method and
collect
the results. We then
call the
averagingInt
method, which takes a lambda expression in order to convert each
element in the
Stream
into an
int
before averaging the values. There are also overloaded op-
erations for the
double
and
long
types, which let you convert your element into these type
of values.
Back in
Primitives
, we talked about how the primitive specialized variants of streams, such
as
IntStream
, had additional functionality for numerical operations. In fact, there are also a
group of collectors that offer similar functionality, in the vein of
averagingInt
. You can add