Java Reference
In-Depth Information
Example 3-1 , there was only one loop. It looks like you would need two here, as there are
two operations. In fact, the library has been cleverly designed so that it iterates over the list
of artists only once.
In Java, when you call a method it traditionally corresponds to the computer actually doing
something; for example, System.out.println("Hello World"); prints output to your ter-
minal. Some of the methods on Stream work a little bit differently. They are normal Java
methods, but the Stream object returned isn't a new collection—it's a recipe for creating a
new collection. So just think for a second about what the code in Example 3-4 does. Don't
worry if you get stuck—I'll explain in a bit!
Example 3-4. Just the filter, no collect step
allArtists . stream ()
. filter ( artist -> artist . isFrom ( "London" ));
It actually doesn't do very much at all—the call to filter builds up a Stream recipe, but
there's nothing to force this recipe to be used. Methods such as filter that build up the
Stream recipe but don't force a new value to be generated at the end are referred to as lazy .
Methods such as count that generate a final value out of the Stream sequence are called
eager .
The easiest way of seeing that is if we add in a println statement as part of the filter in or-
der to print out the artists' names. Example 3-5 is a modified version of Example 3-4 with
such a printout. If we run this code, the program doesn't print anything when it's executed.
Example 3-5. Not printing out artist names due to lazy evaluation
allArtists . stream ()
. filter ( artist -> {
System . out . println ( artist . getName ());
return
return artist . isFrom ( "London" );
});
If we add the same printout to a stream that has a terminal step, such as the counting opera-
tion from Example 3-3 , then we will see the names of our artists printed out ( Example 3-6 ) .
Example 3-6. Printing out artist names
long
long count = allArtists . stream ()
. filter ( artist -> {
System . out . println ( artist . getName ());
return
return artist . isFrom ( "London" );
Search WWH ::




Custom Search