Java Reference
In-Depth Information
Chapter 13
Streams
In this chapter, you will learn
•
What streams are
•
Differences between collections and streams
•
How to create streams from different types of data sources
Optional
class
•
How to represent an optional value using the
•
Applying different types of operations on streams
•
Collecting data from streams using collectors
•
Grouping and partitioning a stream's data
•
Finding and matching data in streams
•
How to work with parallel streams
What Is a Stream?
An
aggregate operation
computes a single value from a collection of values. The result of an aggregate operation may
be simply a primitive value, an object, or a
void
. Note that an object may represent a single entity such as a person or a
collection of values such as a list, a set, a map, etc.
A
stream
is a sequence of data elements supporting sequential and parallel aggregate operations. Computing the
sum of all elements in a stream of integers, mapping all names in list to their lengths, etc. are examples of aggregate
operations on streams.
Looking at the definition of streams, it seems that they are like collections. So, how do streams differ from
collections? Both are abstractions for a collection of data elements. Collections focus on storage of data elements
for efficient access whereas streams focus on aggregate computations on data elements from a data source that is
typically, but not necessarily, collections.
In this section, I will discuss the following features of streams, comparing them with collections when necessary:
•
Streams have no storage.
•
Streams can represent a sequence of infinite elements.
•
The design of streams is based on internal iteration.
•
Streams are designed to be processed in parallel with no additional work from the developers.
•
Streams are designed to support functional programming.