Difference Between Streams and Collections in Java
Difference Between Streams and Collections in Java
Collections in Java
Collection is an in-memory data structure, which holds all the values that the data structure
currently has. Every element in the Collection has to be computed before we add it to the Collection.
Operations such as searching, sorting, insertion, manipulation, and deletion can be performed on a
Collection. It provides many interfaces like (Set, List, Queue, Deque) and Classes like (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet).
On the other hand, IStream is an API that is introduced in Java 8 which is used to process
collections of objects. A stream is a sequence of objects that supports various methods which can be
pipelined to produce the desired result. The Stream API is used to process collections of objects.
A stream is not a data structure instead it takes input from the Collections, Arrays, or
I/O channels.
Streams don’t change the original data structure, they only provide the result as per
the pipelined methods.
Each intermediate operation is lazily executed and returns another stream as a result,
hence various intermediate operations can be pipelined. Terminal operations mark the
end of the stream and return the result.
Example 1: Collections
// Main class
class GFG {
Example: Streams
// Main class
class GFG {
STREAMS COLLECTIONS
It doesn’t store data, it operates
It stores/holds all the data that the data structure currently
on the source data structure i.e
has in a particular data structure like Set, List or Map,
collection.
They use functional interfaces
like lambda which makes it a
They don’t use functional interfaces.
good fit for programming
language.
Java Streams are consumable
They are non-consumable i.e; can be traversable multiple
i.e; to traverse the stream, it
times without creating it again.
needs to be created every time.
Java streams support both It supports parallel processing and parallel processing can be
STREAMS COLLECTIONS
sequential and parallel
very helpful in achieving high performance.
processing.
Specific classes for primitive types such as IntStream,
All the Java stream API LongStream, and DoubleStream are used in collections
interfaces and classes are in since primitive data types such as int, long in the collections
java.util.stream package. using auto-boxing and these operations could take a lot of
time.
Streams are not modifiable i.e
These are modifiable i.e one can easily add to or remove
one can’t add or remove
elements from collections.
elements from streams.
Streams are iterated internally
by just mentioning the Collection
operations.