Java.Java8.What is the difference between Collection and Stream?

Understanding the difference between Collection and Stream is essential to writing clean, modern Java code.

Let’s break it down in a clear and structured way.


✅ Quick Summary

FeatureCollectionStream
💾 Stores Data✅ Yes — stores elements in memory❌ No — processes elements from a source
🔁 Reusable✅ Yes — can iterate multiple times❌ No — can be used only once
🐢 Eager vs LazyEager — holds all data immediatelyLazy — computations done on demand
🔧 Mutability✅ Mutable (add, remove, etc.)❌ Immutable — doesn’t change data source
💬 PurposeData storageData processing (transform/filter/map)
🧵 ParallelismManual (via threads or parallel loops)Built-in with parallelStream()

✅ What is a Collection?

A Collection is:

  • A container of elements (e.g. List, Set, Queue)
  • Stored fully in memory
  • Used to store and retrieve elements
  • Supports adding/removing/modifying

Example:

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");

System.out.println(names); // [Alice, Bob]

✅ What is a Stream?

A Stream is:

  • A view over data from a source (like a Collection, array, file, etc.)
  • Designed for processing data with operations like map(), filter(), reduce()
  • Does not store data
  • Single-use: once consumed, it’s gone

Example:

List<String> names = List.of("Alice", "Bob", "Charlie");

names.stream()
    .filter(name -> name.length() > 3)
    .map(String::toUpperCase)
    .forEach(System.out::println);

🧠 Analogy

ConceptAnalogy
CollectionA basket that holds fruits
StreamA conveyor belt processing each fruit one by one

❓ Can I convert between them?

Yes!

  • From Collection to Stream:
List<String> list = List.of("a", "b");
Stream<String> stream = list.stream();

From Stream to Collection:

List<String> result = stream.collect(Collectors.toList());

🛠 When to Use What?

Use CaseUse
Store and access dataCollection
Mutate or sort data manuallyCollection
Process data in a pipelineStream
Apply functional operationsStream (map, filter, reduce, etc.)
Handle big/lazy data sourcesStream (possibly infinite, like generate)

✅ Summary

AspectCollectionStream
PurposeStores and organizes dataProcesses data in a pipeline
Reusability✅ Reusable❌ One-time use
Data holding✅ Holds all elements in memory❌ No storage — views/flows over a source
OperationsCRUD (add/remove/search)Functional (map/filter/reduce)
EvaluationEagerLazy (until terminal operation is called)
This entry was posted in Без рубрики. Bookmark the permalink.