Java Reference
In-Depth Information
high-calorie dishes.” You don't implement the filtering (filter), extracting (map), or truncating
(limit) functionalities; they're available through the Streams library. As a result, the Streams API
has more flexibility to decide how to optimize this pipeline. For example, the filtering, extracting,
and truncating steps could be merged into a single pass and stop as soon as three dishes are
found. We show an example to demonstrate that in the next chapter.
Let's now stand back a little and examine the conceptual differences between the Collections API
and the new Streams API, before we explore in more detail what operations you can perform
with a stream.
4.3. Streams vs. collections
Both the existing Java notion of collections and the new notion of streams provide interfaces to
data structures representing a sequenced set of values of the element type. By sequenced , we
mean that we commonly step through the values in turn rather than randomly accessing them in
any order. So what's the difference?
We'll start with a visual metaphor. Consider a movie stored on a DVD. This is a collection
(perhaps of bytes or of frames—we don't care which here) because it contains the whole data
structure. Now consider watching the same video when it's being streamed over the internet.
This is now a stream (of bytes or frames). The streaming video player needs to have downloaded
only a few frames in advance of where the user is watching, so you can start displaying values
from the beginning of the stream before most of the values in the stream have even been
computed (consider streaming a live football game). Note particularly that the video player may
lack the memory to buffer the whole stream in memory as a collection—and the startup time
would be appalling if you had to wait for the final frame to appear before you could start
showing the video. You might choose for video-player implementation reasons to buffer a part
of a stream into a collection, but this is distinct from the conceptual difference.
In coarsest terms, the difference between collections and streams has to do with when things are
computed. A collection is an in-memory data structure that holds all the values the data
structure currently has—every element in the collection has to be computed before it can be
added to the collection. (You can add things to, and remove them from, the collection, but at
each moment in time, every element in the collection is stored in memory; elements have to be
computed before becoming part of the collection.)
By contrast, a stream is a conceptually fixed data structure (you can't add or remove elements
from it) whose elements are computed on demand . This gives rise to significant programming
benefits. In chapter 6 we show how simple it is to construct a stream containing all the prime
 
Search WWH ::




Custom Search