Comparing Collections and Streams

It is important to understand the distinction between collections and streams. Streams are not collections, and vice versa, but a stream can be created with a collection as the data source (p. 897).

Collections are data structures that can be used to store and retrieve elements. Streams are data structures that do not store their elements, but process them by expressing computations on them through operations like filter() and collect().

Typically, operations are provided to add or remove elements from a collection. However, no elements can be added or removed from a stream—that is, streams are immutable. Because of their functional nature, if a stream operation does remove or discard an element in a stream, a new stream is returned with the remaining elements. A stream operation does not mutate its data source.

A collection can be used in the program as long as there is a reference to it. However, a stream cannot be reused once it is consumed. It must be re-created on the data source in order to be reused.

Operations on a collection are executed immediately, whereas streams can define intermediate operations that are executed on demand—that is, by lazy execution.

Collections are iterable, but streams are not iterable. Streams do not implement the Iterable<T> interface, and therefore, a for(:) loop cannot be used to iterate over a stream.

Mechanisms for iteration over a collection are based on an iterator defined by the Collection interface, but must be explicitly used in the program to iterate over the elements; this is called external iteration. On the other hand, iteration over stream elements is implicitly handled by the API; this is called internal iteration and it occurs when the stream operations are executed.

Collections have a finite size, but streams can be unbounded; these are called infinite streams. Special stream operations, such as limit(), exist to compute with infinite streams.

Some collections, such as lists, allow positional access of their elements with an index. However, this is not possible with streams, as only aggregate operations are permissible.

Note also that streams supported by the Stream API are not the same as those supported by the File I/O APIs (§20.1, p. 1233).

Leave a Reply

Your email address will not be published. Required fields are marked *