Collection.stream() Method in Java
Collection.stream() is a default method of the java.util.Collection interface, added in Java 8, that returns a sequential Stream over the elements of the collection. Because List, Set and Queue all extend Collection, it is the most common way to start a stream pipeline.
It is a stream creation operation. Its sister method, parallelStream(), returns a possibly parallel stream. This tutorial explains how the collection type affects order and performance, how maps are streamed, and what happens if the collection changes before the stream runs.
1. Syntax and Method Signature
// java.util.Collection<E> (Java 8)
default Stream<E> stream() // sequential stream over this collection
default Stream<E> parallelStream() // possibly parallel stream over this collection
Spliterator<E> spliterator() // the source both methods use
E is the collection's element type, so a List<Invoice> gives a Stream<Invoice>. The default implementation calls StreamSupport.stream(spliterator(), false); collections such as ArrayList provide efficient spliterators of their own.
List<Invoice> invoices = repository.findAll();
double unpaid = invoices.stream()
.filter(Invoice::isUnpaid)
.mapToDouble(Invoice::amount)
.sum();
2. How Collection.stream() Works
stream() does not copy the collection. It wraps the collection's Spliterator, which reads elements directly from the underlying data structure when the terminal operation runs. The spliterator also reports characteristics: an ArrayList is ORDERED and SIZED, a HashSet is DISTINCT but not ordered, and a TreeSet is SORTED.
Most JDK collections use a late-binding spliterator: it binds to the elements when the first element is requested, not when stream() is called. Changes made between creating the stream and running the terminal operation are therefore visible. Changes made during the terminal operation are not allowed and usually throw ConcurrentModificationException.
3. Java Examples
Example 1: Streaming a List of objects (Java 16+)
From a list of invoices, total the unpaid amount for one customer.
import java.util.List;
public class UnpaidInvoiceTotal {
record Invoice(String customer, double amount, boolean paid) { }
public static void main(String[] args) {
List<Invoice> invoices = List.of(
new Invoice("Acme", 1800.0, false),
new Invoice("Zenith", 950.0, false),
new Invoice("Acme", 400.0, true),
new Invoice("Acme", 2250.0, false));
double unpaidForAcme = invoices.stream()
.filter(invoice -> invoice.customer().equals("Acme"))
.filter(invoice -> !invoice.paid())
.mapToDouble(Invoice::amount)
.sum();
System.out.println("Acme owes: " + unpaidForAcme);
}
}
Acme owes: 4050.0
How it works: invoices.stream() reads the list in index order. Two filters narrow it down, and mapToDouble() switches to a DoubleStream so that sum() can add the amounts without boxing.
Example 2: Streaming a Map through its views (Java 9+)
A warehouse keeps stock levels in a map. List the items below the reorder level, and compute the total units in stock.
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class StockMapStream {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>(Map.of(
"bolts", 1200, "hinges", 35, "nails", 80, "screws", 15));
String lowStock = stock.entrySet().stream()
.filter(entry -> entry.getValue() < 100)
.map(entry -> entry.getKey() + "(" + entry.getValue() + ")")
.collect(Collectors.joining(", "));
int totalUnits = stock.values().stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Reorder: " + lowStock);
System.out.println("Total units: " + totalUnits);
}
}
Reorder: hinges(35), nails(80), screws(15) Total units: 1330
How it works: Map is not a Collection, so it has no stream() method. Its entrySet(), keySet() and values() views are collections, so you stream one of them. A TreeMap streams its entries in key order.
Example 3: Late binding sees changes made before the terminal operation (Java 9+)
Create a stream from an ArrayList, add one more element, and then run the terminal operation.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class LateBindingDemo {
public static void main(String[] args) {
List<String> queue = new ArrayList<>(List.of("job-1", "job-2"));
Stream<String> pending = queue.stream(); // stream created
queue.add("job-3"); // collection changed afterwards
System.out.println("Jobs seen by the stream: " + pending.count());
}
}
Jobs seen by the stream: 3
How it works: The ArrayList spliterator binds to the list's contents when the terminal operation starts, so job-3 is counted. This is documented behaviour for late-binding spliterators, but relying on it makes code hard to follow; create the stream right before you use it.
Example 4: Order depends on the collection type (Java 9+)
Stream the same tags from a LinkedHashSet and a TreeSet, and see the different orders.
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class CollectionOrder {
public static void main(String[] args) {
List<String> tags = List.of("spring", "java", "kafka", "java", "docker");
Set<String> insertionOrder = new LinkedHashSet<>(tags);
Set<String> sortedOrder = new TreeSet<>(tags);
System.out.println("LinkedHashSet: " + insertionOrder.stream().collect(Collectors.joining(" ")));
System.out.println("TreeSet: " + sortedOrder.stream().collect(Collectors.joining(" ")));
}
}
LinkedHashSet: spring java kafka docker TreeSet: docker java kafka spring
How it works: Both sets removed the duplicate java. The LinkedHashSet stream follows insertion order and the TreeSet stream follows sorted order. A plain HashSet would give an order you should not rely on.
4. Real-World Use Cases
- Service layers: repositories return a
List<Entity>, and services stream it to filter, map to DTOs and sort. - Reporting on maps:
map.entrySet().stream()finds top-selling products or accounts above a balance. - Deduplicated input: streaming a
Setof user ids that has already removed duplicates.
5. Important Points
- Empty collections give empty streams; no special check is needed.
- Null elements in the collection are streamed as
null; filter them withObjects::nonNullif they can occur. - Modifying the collection during the terminal operation can throw
ConcurrentModificationException. - Concurrent collections such as
ConcurrentHashMapandCopyOnWriteArrayListprovide weakly consistent streams that never throw that exception. - Thread safety: streaming a plain
ArrayListwhile another thread writes to it is unsafe. - Performance:
ArrayListand arrays split efficiently forparallelStream();LinkedListdoes not.
6. Collection.stream() vs Related Methods
| Method | Defined on | Mode | Notes |
|---|---|---|---|
stream() | Collection | Sequential | Default way to start a pipeline |
parallelStream() | Collection | Possibly parallel | May still run sequentially; see parallel() vs parallelStream() |
Stream.of(...) | Stream | Sequential | For values written in code |
Arrays.stream(arr) | Arrays | Sequential | For arrays, including primitive arrays |
map.entrySet().stream() | Map view | Sequential | The usual way to stream a map |
7. Common Mistakes and Best Practices
Calling stream() on a Map
Map<String, Integer> stock = ...;
stock.stream(); // does not compile: Map has no stream() method
Stream a view instead: stock.entrySet().stream(), stock.keySet().stream() or stock.values().stream().
Removing elements while streaming
Use removeIf() to change a collection in place, rather than removing inside forEach():
import java.util.ArrayList;
import java.util.List;
public class RemoveIfInsteadOfStream {
public static void main(String[] args) {
List<String> sessions = new ArrayList<>(List.of("s1:active", "s2:expired", "s3:active", "s4:expired"));
sessions.removeIf(session -> session.endsWith("expired"));
System.out.println(sessions);
}
}
[s1:active, s3:active]
Other mistakes to avoid
- Relying on
HashSetorHashMaporder. Sort the stream or use aLinkedHashorTreecollection. - Calling
stream()on a possibly null collection. Return empty collections from methods instead ofnull. - Streaming just to call
forEach().collection.forEach(...)does the same without a stream.
8. Summary
stream()is a default method ofCollection(Java 8) that returns a sequential stream over its elements.- The stream does not copy data; it reads the collection through its spliterator when the terminal operation runs.
- Element order follows the collection type: lists and linked sets keep order, tree sets sort, hash sets give no guarantee.
- Maps are streamed through
entrySet(),keySet()orvalues().
9. References
Frequently Asked Questions (FAQ)
Q1. What does Collection.stream() return?
It returns a sequential Stream over the elements of the collection, with the same element type. It is a default method of java.util.Collection, added in Java 8, so every List, Set and Queue has it.
Q2. Why can't I call stream() on a Map?
Map does not extend Collection, so it has no stream() method. Stream one of its views instead: entrySet().stream(), keySet().stream() or values().stream().
Q3. Does stream() copy the collection?
No. The stream reads elements directly from the collection through its Spliterator when the terminal operation runs. That is why changes made before the terminal operation are usually visible, and changes during it are not allowed.
Q4. In what order does a stream from a collection produce elements?
It follows the collection's encounter order: index order for a List, insertion order for LinkedHashSet, sorted order for TreeSet. A HashSet has no defined order, so its stream order is unspecified.
Q5. What is the difference between stream() and parallelStream()?
stream() returns a sequential stream. parallelStream() returns a possibly parallel stream that may split the work across threads of the common ForkJoinPool when the terminal operation runs.