Java Reference
In-Depth Information
Example 5-8. Partitioning a stream of artists into bands and solo artists
public
public Map < Boolean , List < Artist >> bandsAndSolo ( Stream < Artist > artists ) {
return
return artists . collect ( partitioningBy ( artist -> artist . isSolo ()));
}
We can also write this using method references, as demonstrated in Example 5-9 .
Example 5-9. Partitioning up a stream of artists into bands and solo artists using a method
reference
public
public Map < Boolean , List < Artist >> bandsAndSoloRef ( Stream < Artist > artists ) {
return
return artists . collect ( partitioningBy ( Artist: : isSolo ));
}
Grouping the Data
There's a natural way to generalize partitioning through altering the grouping operation. It's
more general in the sense that instead of splitting up your data into true and false groups,
you can use whatever values you want. Perhaps some code has given you a Stream of al-
bums and you want to group them by the name of their main musician. You might write
some code like Example 5-10 .
Example 5-10. Grouping albums by their main artist
public
public Map < Artist , List < Album >> albumsByArtist ( Stream < Album > albums ) {
return
return albums . collect ( groupingBy ( album -> album . getMainMusician ()));
}
As with the other examples, we're calling collect on the Stream and passing in a Collect-
or . Our groupingBy collector ( Figure 5-2 ) takes a classifier function in order to partition
the data, just like the partitioningBy collector took a Predicate to split it up into true
and false values. Our classifier is a Function —the same type that we use for the common
map operation.
Search WWH ::




Custom Search