Java Reference
In-Depth Information
numbers (2,3,5,7,11,...) even though there are an infinite number of them. The idea is that a user
will extract only the values they require from a stream, and these elements are
produced—invisibly to the user—only as and when required. This is a form of a
producer-consumer relationship. Another view is that a stream is like a lazily constructed
collection: values are computed when they're solicited by a consumer (in management speak
this is demand-driven, or even just-in-time, manufacturing).
In contrast, a collection is eagerly constructed (supplier-driven: fill your warehouse before you
start selling, like a Christmas novelty that has a limited life). Applying this to the primes
example, attempting to construct a collection of all prime numbers would result in a program
loop that forever computes a new prime, adding it to the collection, but of course could never
finish making the collection, so the consumer would never get to see it.
Figure 4.3 illustrates the difference between a stream and a collection applied to our DVD vs.
internet streaming example.
Figure 4.3. Streams vs. collections
Another example is a browser internet search. Suppose you search for a phrase with many
matches in Google or in an e-commerce online shop. Instead of waiting for the whole collection
 
Search WWH ::




Custom Search