Java Reference
In-Depth Information
One reason, then, why filters can be so much faster than iterators is simply that they can take
advantage of algorithmic opportunities for optimizations: the lazy filter implementation can
end processing whenever it has done what it needs to do, processing less data.
What if the entire set of data must be processed—what is the basic performance of filters
versus iterators in that case? For this example, we'll change the test slightly. The previous
example made a good teaching point about how multiple filters worked, but hopefully it was
obvious that the code would perform better with a single filter:
public
public int
int countSymbols ( ArrayList < String > al ) {
int
int count = 0 ;
t = al . stream ().
filter ( symbol -> symbol . charAt ( 0 ) != 'A' &&
symbol . charAt ( 1 ) != 'A' &&
symbol . charAt ( 2 ) != 'A' &&
symbol . charAt ( 3 ) != 'A' ).
forEach ( symbol -> count ++);
return
return count ;
}
The example here also changes the final code to count the symbols, so that the entire list will
be processed. On the flip side, the eager implementation can now use an iterator directly:
public
public int
int countSymbols ( ArrayList < String > al ) {
int
int count = 0 ;
for
for ( String symbol : al ) {
iif ( symbol . charAt ( 0 ) != 'A' &&
symbol . charAt ( 1 ) != 'A' &&
symbol . charAt ( 2 ) != 'A' &&
symbol . charAt ( 3 ) != 'A' )
count ++;
return
return count ;
}
Even in this case, the lazy filter implementation is faster than the iterator (see Table 12-11 ) .
Search WWH ::




Custom Search