Stream vs Collection in Java
A Collection in Java, such as a List or Set from java.util, is a data structure that stores elements in memory. A Stream, from java.util.stream (Java 8), is a one-time pipeline that reads elements from a source and computes a result. In short, a collection is about holding data and a stream is about processing it.
This tutorial compares the two side by side: when values are computed, how often they can be traversed, whether they can be infinite, how they handle changes, and how to convert one into the other. All examples were compiled and run on Java 25.
1. Stream vs Collection at a Glance
| Aspect | Collection | Stream |
|---|---|---|
| Main purpose | Store and manage elements | Compute a result from elements |
| Storage | Holds all elements in memory | Holds nothing; pulls from a source |
| Evaluation | Eager: elements exist before you use them | Lazy: elements are computed when the terminal operation needs them |
| Traversal | Any number of times | Once; a second terminal operation throws IllegalStateException |
| Size | Finite | Finite or infinite (iterate(), generate()) |
| Modification | add(), remove(), removeIf() | Not possible; operations return new streams or results |
| Iteration style | External (for-each, Iterator) | Internal (the library runs the loop) |
| Parallelism | Your own threads | parallel() or parallelStream() |
| Element access | list.get(i), contains() | No index access; search with filter() or anyMatch() |
2. How Collections and Streams Differ
A collection is eager: by the time you hold an ArrayList, every element has already been computed and stored. A stream is lazy: list.stream().map(...) only records the step. When a terminal operation runs, each element is read from the source and pushed through the steps one at a time, so the stream never needs to keep more than it must.
The two work together. Most pipelines start from a collection with collection.stream() and end in a new collection with toList() or a collector. The collection gives you storage and random access; the stream gives you a concise, one-pass computation.
3. Java Examples
Example 1: Eager collection, lazy stream (Java 9+)
A price service converts product codes into prices, which is slow. Compare building the full list first with asking a stream for the first expensive item.
import java.util.ArrayList;
import java.util.List;
public class EagerVsLazy {
static int lookUpPrice(String code) {
System.out.println(" looking up " + code);
return code.length() * 100;
}
public static void main(String[] args) {
List<String> codes = List.of("PEN", "LAMP", "DESK", "CHAIR");
System.out.println("Collection (eager):");
List<Integer> prices = new ArrayList<>();
for (String code : codes) {
prices.add(lookUpPrice(code));
}
System.out.println(" first price over 350: " + prices.stream().filter(p -> p > 350).findFirst().get());
System.out.println("Stream (lazy):");
int first = codes.stream()
.map(EagerVsLazy::lookUpPrice)
.filter(p -> p > 350)
.findFirst()
.get();
System.out.println(" first price over 350: " + first);
}
}
Collection (eager): looking up PEN looking up LAMP looking up DESK looking up CHAIR first price over 350: 400 Stream (lazy): looking up PEN looking up LAMP first price over 350: 400
How it works: The list has to compute all four prices before you can search it. The stream computes prices one by one and stops after LAMP, because findFirst() already has its answer. DESK and CHAIR are never looked up.
Example 2: Changing a collection compared with deriving a new one (Java 16+)
An order desk must drop cancelled orders. removeIf() changes the collection itself; a stream leaves the source as it is and returns a new list.
import java.util.ArrayList;
import java.util.List;
public class ModifyVsDerive {
record Order(int id, String status) { }
public static void main(String[] args) {
List<Order> source = List.of(new Order(1, "PAID"), new Order(2, "CANCELLED"),
new Order(3, "PAID"), new Order(4, "CANCELLED"));
List<Order> editable = new ArrayList<>(source);
editable.removeIf(order -> order.status().equals("CANCELLED"));
System.out.println("removeIf changed the list: " + editable.size() + " orders left");
List<Order> paid = source.stream()
.filter(order -> order.status().equals("PAID"))
.toList();
System.out.println("Stream built a new list: " + paid.size() + " orders");
System.out.println("Source still has: " + source.size() + " orders");
}
}
removeIf changed the list: 2 orders left Stream built a new list: 2 orders Source still has: 4 orders
How it works: Collections are mutable containers (unless they are created unmodifiable), so removeIf() edits them in place. Streams never edit; they always produce something new. toList() and records need Java 16.
Example 3: A stream can be infinite, a collection cannot
A help desk issues ticket numbers starting at 1001. You can describe all future ticket numbers as a stream and take only the ones you need.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class InfiniteTickets {
public static void main(String[] args) {
Stream<String> allTickets = Stream.iterate(1001, n -> n + 1)
.map(n -> "TKT-" + n);
List<String> nextFive = allTickets.limit(5).collect(Collectors.toList());
System.out.println(nextFive);
}
}
[TKT-1001, TKT-1002, TKT-1003, TKT-1004, TKT-1005]
How it works: allTickets describes an endless sequence, which no collection could hold. Because elements are produced on demand, limit(5) asks for exactly five and the stream stops.
Example 4: Converting between collections and streams (Java 9+)
Turn a list of city visits with duplicates into a sorted set, and into a map from each city to its name length, keeping first-seen order.
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CollectionConversions {
public static void main(String[] args) {
List<String> visits = List.of("Pune", "Goa", "Agra", "Goa", "Pune", "Kochi");
Set<String> sortedCities = visits.stream()
.collect(Collectors.toCollection(TreeSet::new));
Map<String, Integer> nameLengths = visits.stream()
.distinct()
.collect(Collectors.toMap(Function.identity(), String::length,
(first, second) -> first, LinkedHashMap::new));
System.out.println("Sorted set: " + sortedCities);
System.out.println("Map: " + nameLengths);
System.out.println("Back to a stream: " + sortedCities.stream().count() + " cities");
}
}
Sorted set: [Agra, Goa, Kochi, Pune]
Map: {Pune=4, Goa=3, Agra=4, Kochi=5}
Back to a stream: 4 cities
How it works: stream() turns any collection into a stream, and collectors turn a stream back into exactly the collection type you need: toCollection(TreeSet::new) for a sorted set, and the four-argument toMap() for a LinkedHashMap that keeps order.
4. Real-World Use Cases
- Keep data in collections, compute with streams: an inventory service stores products in a
Mapfor fast lookup, and uses streams to build low-stock reports. - Paging through large results: a stream over a database cursor or file reads only the rows a page needs, while a list would load everything.
- Caching computed views: a dashboard computes a summary once with a stream and stores it in an unmodifiable list to read many times.
5. Important Points
- Converting costs memory. Collecting a large stream into a list materialises every element; keep the pipeline going if you only need an aggregate.
- Order of the result follows the source. A stream from a
HashSethas no defined order, so sort it if the output order matters. - Unmodifiable results:
Stream.toList()returns an unmodifiable list; usetoCollection(ArrayList::new)when you must edit it. - Duplicates: a
Listkeeps them, aSetremoves them; in a stream usedistinct(). - Thread safety: neither an
ArrayListnor a stream pipeline is thread-safe by itself; do not share a mutable collection across parallel lambdas.
6. Common Mistakes and Best Practices
Treating a stream like a collection
Storing a stream and using it twice fails, because a stream is consumed by its terminal operation:
Stream<String> names = employees.stream().map(Employee::name);
long count = names.count();
List<String> list = names.toList(); // IllegalStateException
If you need the data more than once, store a collection, which can be read any number of times:
import java.util.List;
public class StoreTheCollection {
public static void main(String[] args) {
List<String> names = List.of("Nisha", "Arjun", "Leela").stream()
.map(String::toUpperCase)
.toList(); // materialise once
System.out.println("Count: " + names.size());
System.out.println("Names: " + names);
}
}
Count: 3 Names: [NISHA, ARJUN, LEELA]
Other mistakes to avoid
- Collecting just to count.
list.stream().filter(...).toList().size()builds a list for nothing; usecount(). - Using a stream for a single lookup by index.
list.get(3)is clearer and faster thanskip(3).findFirst(). - Streaming a collection to change it. Use
removeIf(),replaceAll()or a new collection, not side effects inforEach().
7. Summary
- A collection stores elements and can be read and changed many times.
- A stream stores nothing, computes lazily and is consumed by one terminal operation.
- Only streams can describe infinite sequences, because they compute elements on demand.
- Use
stream()to go from a collection to a stream, andtoList()or a collector to go back.
8. References
Frequently Asked Questions (FAQ)
Q1. What is the main difference between a Stream and a Collection?
A collection stores elements in memory and can be read and changed many times. A stream stores nothing; it reads elements from a source, computes a result lazily and can be used only once.
Q2. Is a Java stream a data structure?
No. A stream is a view of a computation over a source, such as a collection or an array. It does not hold elements and offers no add, remove or index-based access.
Q3. Can a stream be infinite while a collection cannot?
Yes. Stream.iterate() and Stream.generate() describe endless sequences because elements are produced on demand. Limit them with limit() or takeWhile() before a terminal operation that needs every element.
Q4. How do I convert a stream back into a collection?
Call toList() for an unmodifiable list, or collect() with a collector such as Collectors.toSet(), Collectors.toMap() or Collectors.toCollection(TreeSet::new) when you need a specific collection type.
Q5. When should I use a collection instead of a stream?
Use a collection when you need to store data, access it by index or key, read it several times or change it. Use a stream when you want to transform, filter or summarise data in a single pass.