Sobes.tech
Middle

What is the difference between Collection and Stream in Java?

sobes.tech AI

Answer from AI

Collection — a data structure for storing elements, representing a group of objects, such as lists or sets. It is a data repository focused on managing elements.

Stream — a sequence of elements from a source (e.g., a collection), supporting operations for processing and analyzing these elements in a functional style. It does not store data but merely represents a data flow for performing operations.

Main differences:

  • Purpose: Collection - data storage, Stream - data processing.
  • State change: Operations on Collection usually modify its state. Stream operations do not change the original data source.
  • Reusability: Collection can be used multiple times. Stream is usually single-use after a terminal operation.
  • Laziness: Operations on Stream are performed "lazily" (only when a terminal operation is invoked), which can be efficient for large data sets. Collection operations are executed immediately.
  • Parallelism: Stream supports efficient parallelism using the parallelStream() method.

Example:

// Collection: storing iterable data
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

// Stream: processing data from the collection
long count = names.stream() // creating a stream from the collection
                  .filter(name -> name.startsWith("A")) // intermediate operation
                  .count(); // terminal operation
What is the difference between Collection and Stream… - sobes.tech