Stream vs Collection in Java

Introduction

In this tutorial, we will try to understand the difference between Stream and Collection in Java.

Streams vs. Collections

Stream and Collection both provide interfaces to iterate over the elements most of the time in a particular order. So what is the difference between these two?

A collection is an in-memory data structure that contains all the values the data structure currently has—every element in the collection has to be calculated before it can be joined to the collection.  You can add items to, and remove them from, the collection, but at each time, each element in the collection is stored in memory; elements have to be calculated before becoming member of the collection.

A stream is a conceptually fixed data structure (you can’t add or remove elements from it) whose elements are computed on request.

Collection is eagerly constructed while Stream is lazily constructed.

For example— When you drinking water using glass, it is a form of a collection, you are storing water into a glass then drinking it. While if you will drink water directly from the water tap, It is a form of stream.

Using Netflix for watching a movie is a form of Stream (Complete movie is not stored only a few frames are buffered into the memory) while watching a movie from a DVD is the example of the collection (All data is computed and stored before starting the movie.)

Summary

1. Collection is eagerly constructed while Stream is lazily constructed.

2. Stream could be traversed only once while Collection could be traversed any number of times.

   For Example— This code will throw java.lang.IllegalStateException.

List list = new ArrayList<>();
list.add(1);
list.add(2);
	
Stream stream = list.stream();
	
stream.forEach(System.out::println);
stream.forEach(System.out::println);

3. The collection is externally traversable while stream uses the internal traversable technique.