Streams in Java

Streams in Java #

A Java stream is a sequence of objects.

When it is finite, a stream may be viewed as a list with limitations: a stream can only be iterated over, from left to right, and only once (this is called consuming a stream).

Stream vs Collection #

The Javadoc for the package java.util.stream summarizes key differences between a Java Stream and a Java Collection (like a List):

  • No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source (such as an array) through a pipeline of computational operations.
  • Functional in nature. An operation on a stream produces a result, but does not modify its source. For example, filtering a stream obtained from a collection produces a new stream without the filtered elements, rather than removing elements from the source collection.
  • Laziness-seeking. Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization.
  • Possibly unbounded. While collections have a finite size, streams need not.
  • Consumable. The elements of a stream are only visited once during the life of a stream.

Parallelization #

Another important feature of Java stream is native support for multithreading, with a high-level syntax.