Java Reference
In-Depth Information
This example finds the names of all tracks that are over a minute in length, given some al-
bums. Our legacy code is shown in Example 3-19 . We start off by initializing a Set that
we'll store all the track names in. The code then iterates, using a for loop, over all the al-
bums, then iterates again over all the tracks in an album. Once we've found a track, we check
whether the length is over 60 seconds, and if it is the name gets added to a Set of names.
Example 3-19. Legacy code finding names of tracks over a minute in length
public
public Set < String > findLongTracks ( List < Album > albums ) {
Set < String > trackNames = new
new HashSet <>();
for
for ( Album album : albums ) {
for
for ( Track track : album . getTrackList ()) {
iif ( track . getLength () > 60 ) {
String name = track . getName ();
trackNames . add ( name );
}
}
}
return
return trackNames ;
}
We've stumbled across this code in our code base and noticed that it has a couple of nested
loops. It's not quite clear what the purpose of this code is just from looking at it, so we de-
cide to undertake our refactor. (There are lots of different approaches to refactoring legacy
code for using streams—this is just one. In fact, once you are more familiar with the API it-
self, it's pretty likely that you won't need to proceed in such small steps. It serves education-
al purposes here to go a bit slower than you would in your professional job.)
The first thing that we're going to change is the for loops. We'll keep their bodies in the ex-
isting Java coding style for now and move to using the forEach method on Stream . This can
be a pretty handy trick for intermediate refactoring steps. Let's use the stream method on
our album list in order to get the first stream. It's also good to remember from the previous
section that our domain already has the getTracks method on the album, which provides us
a Stream of tracks. The code after we've completed step 1 is listed in Example 3-20 .
Example 3-20. Refactor step 1: finding names of tracks over a minute in length
public
public Set < String > findLongTracks ( List < Album > albums ) {
Set < String > trackNames = new
new HashSet <>();
albums . stream ()
. forEach ( album -> {
album . getTracks ()
. forEach ( track -> {
Search WWH ::




Custom Search