Senior
What is the difference between a collection and a stream?
sobes.tech AI
Answer from AI
Collection — is a data structure that stores elements in memory and provides methods for adding, removing, and iterating over these elements. A collection is a specific data storage.
Stream — is an abstraction for sequential data processing that does not store elements but allows performing operations on them (filtering, mapping, aggregation) in a functional style. Streams are lazy and can be single-use.
Key differences:
- Collection stores data, stream does not.
- Collection can be iterated multiple times, stream is single-use.
- Stream supports chaining operations and lazy evaluation.
Example:
List<String> list = Arrays.asList("a", "b", "c");
// Collection stores data
for (String s : list) {
System.out.println(s);
}
// Stream allows functional data processing
list.stream()
.filter(s -> !s.equals("b"))
.forEach(System.out::println);