Collections vs Streams in java 8

Java 8 has introduced new feature named Stream API’s , So many of you may think what are benefits of Stream API over existing Collection API . In this article we will see benefits of Stream API  and difference between Collection and Stream.

Introduction

In order to visualize the collection and stream , consider example of playing video from DVD and streamed over internet.

Collection :  Video stored on DVD. This is considered as collection where whole data structure is stored in memory when we play it using video player.

Stream :  Streaming of video over internet can be considered as Stream where only frames which are needed for showing video are  downloaded. It only downloads few frames in advance.

Difference between Streams and Collections

  • Based on computation :  

In Collection, All elements are stored as in-memory data structure. every element has to be computed before it can be added to collection.

In Stream, It is conceptually fixed data structure whose elements are computed on demand.

  • Based on storage :

In  Collection, it is data structure which stores elements i.e. we can add and remove elements from it.

Stream, does not store elements i.e.  we cannot add and remove elements from it.

  • Functional in nature :

In Collection , when we perform operations such as add/remove then it modifies source collection.

In Stream , An operation on a stream does not modify its source. e.g.  if you filter the stream then it doesn’t modify the underlying source collection.

  • Based on construction :

Collection is eagerly constructed  i.e. supplier driven

Stream is lazily constructed i.e. demand driven . Stream doesn’t start processing until it encounters terminal operation(like limit(n) or findFirst()).Intermediate operations like filtering, mapping, or duplicate removal, are implemented lazily.

  • Consumable :

Collections can be consumed multiple times in its lifetime.

Stream can be consumed only once in its lifetime.

Happy Learning !!

Leave a Reply

Your email address will not be published. Required fields are marked *