Java Reference
In-Depth Information
Example 3-18. Imperative implementation of summing
int acc = 0 ;
for ( Integer element : asList ( 1 , 2 , 3 )) {
acc = acc + element ;
assertEquals ( 6 , acc );
In the imperative version, we can see that the accumulator is a variable we update on every
loop iteration. We also update it by adding the element. The loop is external to the collection
and all updates to the variable are managed manually.
Putting Operations Together
With so many different operations related to the Stream interface, it can sometimes seem like
you're wandering around a labyrinth looking for what you want. So let's work through a
problem and see how it breaks down into simple Stream operations.
Our first problem to solve is, for a given album, to find the nationality of every band playing
on that album. The artists who play each track can be solo artists or they can be in a band.
We're going to use domain knowledge and artistic license to pretend that a band is really an
artist whose name begins with The . This isn't exactly right, but it's pretty close!
The first thing to recognize is that the solution isn't just the simple application of any indi-
vidual API call. It's not transforming the values like a map , it's not filtering, and it's not just
getting a single value out of a Stream at the end. We can break the problem down into parts:
1. Get all the artists for an album.
2. Figure out which artists are bands.
3. Find the nationalities of each band.
4. Put together a set of these values.
Now it's easier to see how these steps fit into the API:
1. There's a nice getMusicians method on our Album class that returns a Stream .
2. We use filter to trim down the artists to include only bands.
3. We use map to turn the band into its nationality.
Search WWH ::

Custom Search