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
Collectionusually modify its state.Streamoperations do not change the original data source. - Reusability:
Collectioncan be used multiple times.Streamis usually single-use after a terminal operation. - Laziness: Operations on
Streamare performed "lazily" (only when a terminal operation is invoked), which can be efficient for large data sets.Collectionoperations are executed immediately. - Parallelism:
Streamsupports efficient parallelism using theparallelStream()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