What is a stream?
The best way to understand a stream is to compare it to a collection. The latter is a data structure stored in memory. Every collection element is computed before being added to the collection. In contrast, an element emitted by a stream exists somewhere else (in the source) and is computed on demand. So, a collection can be a source for a stream.
In Java, a stream is an object of a Stream
, IntStream
, LongStream
, or DoubleStream
interface of the java.util.stream
package. All methods present in the Stream
interface are also available (with corresponding type changes) in the IntStream
, LongStream
, or DoubleStream
specialized numeric stream interfaces. Some of the numeric stream interfaces have a few extra methods, such as average()
andsum()
, specific to the numeric values.
In this chapter, we will mostly speak about the Stream
interface and its methods. But everything introduced can be equally applied to the numeric stream interfaces, too. At the end of the chapter, we will...