Java Reference
In-Depth Information
Figure 7-1. ToLongFunction
Now that we've made these decisions, the body of the method follows naturally. We take a
Stream of the albums, map each album to a long , and then sum them. When we implement
the consumer-facing methods such as countTracks , we pass in a lambda expression with be-
havior specific to that domain method. In this case, we're mapping the album to the number
of tracks. Example 7-7 is what our code looks like when we've converted the code to use this
domain-appropriate method.
Example 7-7. A refactor of our Order class to use domain-level methods
public
public long
long countFeature ( ToLongFunction < Album > function ) {
return
return albums . stream ()
. mapToLong ( function )
. sum ();
}
public
public long
long countTracks () {
return
return countFeature ( album -> album . getTracks (). count ());
}
public
public long
long countRunningTime () {
return
return countFeature ( album -> album . getTracks ()
. mapToLong ( track -> track . getLength ())
. sum ());
}
public
public long
long countMusicians () {
return
return countFeature ( album -> album . getMusicians (). count ());
}
Search WWH ::




Custom Search