Java Reference
In-Depth Information
This is exactly what you do every day with your Java collections. You iterate a collection
externally , explicitly pulling out and processing the items one by one. It would be far better if
you could just tell Sofia, “Put all the toys that are on the floor inside the box.” There are two
other reasons why an internal iteration is preferable: first, Sofia could choose to take at the same
time the doll with one hand and the ball with the other, and second, she could decide to take the
objects closest to the box first and then the others. In the same way, using an internal iteration,
the processing of items could be transparently done in parallel or in a different order that may
be more optimized. These optimizations are difficult if you iterate the collection externally as
you're used to doing in Java. This may seem like nit-picking, but it's much of the raison-d'être of
Java 8's introduction of streams—the internal iteration in the Streams library can automatically
choose a data representation and implementation of parallelism to match your hardware. By
contrast, once you've chosen external iteration by writing for-each, then you've essentially
committed to self-manage any parallelism. ( Self-managing in practice means either “one fine
day we'll parallelize this” or “starting the long and arduous battle involving tasks and
synchronized”.) Java 8 needed an interface like Collection but without iterators, ergo Stream!
Figure 4.4 illustrates the difference between a stream (internal iteration) and a collection
(external iteration).
Figure 4.4. Internal vs. external iteration
 
Search WWH ::




Custom Search