Java Reference
In-Depth Information
do is print out the collection value after each step. This is pretty hard with the Streams frame-
work, as intermediate steps are lazily evaluated.
Let's take a look at how we might log intermediate values by taking a look at an imperative
version of our nationality report from Chapter 3 . In case you've forgotten, and who doesn't
sometimes, this is code that tries to find the country of origin for every artist on an album. In
Example 7-16 we're going to log each of the nationalities that we find.
Example 7-16. Logging intermediate values in order to debug a for loop
Set < String > nationalities = new
new HashSet <>();
for
for ( Artist artist : album . getMusicianList ()) {
iif ( artist . getName (). startsWith ( "The" )) {
String nationality = artist . getNationality ();
System . out . println ( "Found nationality: " + nationality );
nationalities . add ( nationality );
}
}
return
return nationalities ;
Now we could use the forEach method to print out the values from the stream, which would
also cause it to be evaluated. However, this way has the downside that we can't continue to
operate on that stream, because streams can only be used once. If we really want to use this
approach, we need to recreate the stream. Example 7-17 shows how ugly this can get.
Example 7-17. Using a naive forEach to log intermediate values
album . getMusicians ()
. filter ( artist -> artist . getName (). startsWith ( "The" ))
. map ( artist -> artist . getNationality ())
. forEach ( nationality -> System . out . println ( "Found: " + nationality ));
Set < String > nationalities
= album . getMusicians ()
. filter ( artist -> artist . getName (). startsWith ( "The" ))
. map ( artist -> artist . getNationality ())
. collect ( Collectors .< String > toSet ());
The Solution: peek
Fortunately, the streams library contains a method that lets you look at each value in turn and
also lets you continue to operate on the same underlying stream. It's called peek . In
Search WWH ::




Custom Search