Java Reference
In-Depth Information
Lazy Traversal
The first performance benefit from streams is that they are implemented as lazy data struc-
tures. Consider the example where we have a list of stock symbols, and the goal is to find the
first symbol in the list that does not contain the letter A . The code to do that through a stream
looks like this:
public String findSymbol ( ArrayList < String > al ) {
Optional < String > t = al . stream ().
filter ( symbol -> symbol . charAt ( 0 ) != 'A' ).
filter ( symbol -> symbol . charAt ( 1 ) != 'A' ).
filter ( symbol -> symbol . charAt ( 2 ) != 'A' ).
filter ( symbol -> symbol . charAt ( 3 ) != 'A' ).
findFirst ();
return t . get ();
There's obviously a better way to implement this using a single filter, but we'll save that dis-
cussion for later. For now, consider what it means for the stream to be implemented lazily in
this example. Each filter() method returns a new stream, so there are in effect four logical
streams here.
The filter() method, it turns out, doesn't really do anything except set up a series of point-
ers. The effect of that is when the findFirst() method is invoked on the stream, no data
processing has been performed—no comparisons of data to the character A have yet been
Instead, the findFirst() asks the previous stream (returned from filter 4) for an element.
That stream has no elements yet, so it calls back to the stream produced by filter 3, and so
on. Filter 1 will grab the first element from the array list (from the stream, technically) and
test to see if its first character is A . If so, it completes the callback and returns that element
downstream; otherwise, it continues to iterate through the array until it finds a matching ele-
ment (or exhausts the array). Filter 2 behaves similarly—when the callback to filter 1 returns,
it tests to see if the second character is A . If so, it completes its callback and passes the sym-
bol downstream; if not, it makes another callback to filter 1 to get the next symbol.
All those callbacks may sound inefficient, but consider the alternative. An algorithm to pro-
cess the streams eagerly would look something like this:
Search WWH ::

Custom Search