Learnitweb

Difference between Streams and Collections in Java

A collection is a group of elements. A collection is an in-memory data structure. Collection supports various operations such as sorting, searching, insertion, manipulation and deletion. In Java, collection framework provides many interfaces like Set, List, Queue and implementation classes like ArrayList, HashSet to represent different type of collections.

Stream is basically a sequence of elements. The basic definition of stream is – A sequence of elements supporting sequential and parallel aggregate operations. Java 8 provided an additional package java.util.stream.

Stream is not a data structure like a collection and does not store elements. It is a sequence of elements. A stream provides an interface to a sequenced set of values of a particular type.

The source of stream might be an array, an I/O channel, a collection, a generator function.

CollectionsStreams
A collection is a group of elements. It is a data structure and stores data.A stream is not a data structure and does not store data. A stream is a sequence of elements. A collection can be a source of stream.
A collection can be traversed multiple times.A stream should be operated only once. A stream implementation may throw IllegalStateException if the stream is being reused.
A collection provides methods to manipulate their elements.Streams do not provide a means to directly access or manipulate their elements. An operation on a stream does not modify its source, but simply produces a result.
A collection is iterated explicitly (external iteration). A stream is internally iterated.
A collection supports parallel execution. But to create such a collection requires more effort in comparison to stream.Stream pipelines may execute either sequentially or parallelly. A stream is a parallel stream, this can be defined at creation itself.
Collections are not lazy in nature. Every element in the collection has to be computed before we add it to the Collection. Operations on collections are not lazy in nature.Streams are lazy in nature. Computation of the source is performed when terminal operation is initiated, and source elements are consumed only as needed.
Collection API is in use since Java 1.2.Streams were added in Java 1.8