Java Reference
In-Depth Information
up the values using summingInt and friends. SummaryStatistics is collectible using sum-
marizingInt and its combinations.
Partitioning the Data
Another common operation that you might want to do with a Stream is partition it into two
collections of values. For example, if you've got a Stream of artists, then you might wish to
get all the artists who are solo artists—that is, who have no fellow band members—and all
the artists who are bands. One approach to doing this is to perform two different filters, one
looking for solo artists and the other for bands.
This approach has a couple of downsides, though. First, you'll need two streams in order to
perform these two stream operations. Second, if you've got a long sequence of operations
leading up to your filters, these will need to be performed twice over each stream. This also
doesn't result in clean code.
Consequently, there is a collector, partitioningBy , that takes a stream and partitions its
contents into two groups (see Figure 5-1 ). It uses a Predicate to determine whether an ele-
ment should be part of the true group or the false group and returns a Map from Boolean to a
List of values. So, the Predicate returns true for all the values in the true List and
false for the other List .
Figure 5-1. The partitioningBy collector
We can use these features to split out bands (artists with more than one member) from solo
artists. In this case, our partitioning function tells us whether the artist is a solo act.
Example 5-8 provides an implementation.
Search WWH ::




Custom Search