Java Reference
In-Depth Information
Data processing operations Streams support database-like operations and common operations
from functional programming languages to manipulate data, such as filter , map , reduce , find ,
match , sort , and so on. Stream operations can be executed either sequentially or in parallel.
In addition, stream operations have two important characteristics:
Pipelining Many stream operations return a stream themselves, allowing operations to be chained
and form a larger pipeline. This enables certain optimizations that we explain in the next chapter, such
as laziness and short-circuiting . A pipeline of operations can be viewed as a database-like query on
the data source.
Internal iteration In contrast to collections, which are iterated explicitly using an iterator,
stream operations do the iteration behind the scenes for you. We briefly mentioned this idea in
chapter 1 and return to it later in the next section.
Let's look at a code example to explain all of these ideas:
In this example, you first get a stream from the list of dishes by calling the stream method on
menu. The data source is the list of dishes (the menu) and it provides a sequence of elements to
the stream. Next, you apply a series of data processing operations on the stream: filter, map,
limit, and collect. All these operations except collect return another stream so they can be
connected to form a pipeline , which can be viewed as a query on the source. Finally, the collect
operation starts processing the pipeline to return a result (it's different because it returns
something other than a stream—here, a List). No result is produced, and indeed no element
from menu is even selected, until collect is invoked. You can think of it as if the method
invocations in the chain are queued up until collect is called. Figure 4.2 shows the sequence of
stream operations: filter, map, limit, and collect, each of which is briefly described here:
 
Search WWH ::




Custom Search