Java Reference
In-Depth Information
System . out . println ( stepThrough . nextInt ());
}
One significant consequence of modeling the infinite stream is that methods like
collect() won't work. This is because we can't materialize the whole stream to a
collection (we would run out of memory before we created the infinite amount of
objects we would need). Instead, we must adopt a model in which we pull the ele‐
ments out of the stream as we need them. Essentially, we need a bit of code that
returns the next element as we demand it. The key technique that is used to accom‐
plish this is lazy evaluation . This essentially means that values are not necessarily
computed until they are needed.
Lazy evaluation is a big change for Java, as until JDK 8 the
value of an expression was always computed as soon as it was
assigned to a variable (or passed into a method). This familiar
model, where values are computed immediately, is called
“eager evaluation” and it is the default behavior for evaluation
of expressions in most mainstream programming languages.
Fortunately, lazy evaluation is largely a burden that falls on the library writer, not
the developer, and for the most part when using the Streams API, Java developers
don't need to think closely about lazy evaluation. Let's finish off our discussion of
streams by looking at an extended code example using reduce() , and calculate the
average word length in some Shakespeare quotes:
String [] billyQuotes = { "For Brutus is an honourable man" ,
"Give me your hands if we be friends and Robin shall restore amends" ,
"Misery acquaints a man with strange bedfellows" };
List < String > quotes = Arrays . asList ( billyQuotes );
// Create a temporary collection for our words
List < String > words = quotes . stream ()
. flatMap ( line -> Stream . of ( line . split ( " +" )));
. collect ( Collectors . toList ());
long wordCount = words . size ();
// The cast to double is only needed to prevent Java from using
// integer division
double aveLength = (( double ) words . stream ()
. map ( String: : length )
. reduce ( 0 , ( x , y ) -> { return x + y ;})) / wordCount ;
System . out . println ( "Average word length: " + aveLength );
In this example, we've introduced the flatMap() method. In our example, it takes in
a single string, line , and returns a stream of strings, which is obtained by splitting
up the line into its component words. These are then “flattened” so that all the sub-
streams from each string are just combined into a single stream.
Search WWH ::




Custom Search