00:00

Collection.stream() Method in Java

Last updated:

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

Collection.java (API)
// 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.

Usage
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.

How the collection type shapes the stream Four rows. ArrayList gives an ordered, sized stream in index order. HashSet gives an unordered stream with no guaranteed order. TreeSet gives an ordered stream in sorted order. A Map has no stream method; you stream entrySet, keySet or values. COLLECTION stream() ELEMENT ORDER ArrayList [3, 1, 2] ordered, sized 3, 1, 2 HashSet {3, 1, 2} unordered, sized not specified TreeSet {1, 2, 3} ordered, sorted 1, 2, 3 HashMap {k=v} entrySet().stream() Map.Entry items
Figure 1: The stream inherits its characteristics from the collection: lists keep index order, tree sets stream in sorted order, and hash sets give no order guarantee.

3. Java Examples

Example 1: Streaming a List of objects (Java 16+)

From a list of invoices, total the unpaid amount for one customer.

UnpaidInvoiceTotal.java
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);
    }
}
Output
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.

StockMapStream.java
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);
    }
}
Output
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.

LateBindingDemo.java
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());
    }
}
Output
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.

CollectionOrder.java
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(" ")));
    }
}
Output
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 Set of 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 with Objects::nonNull if they can occur.
  • Modifying the collection during the terminal operation can throw ConcurrentModificationException.
  • Concurrent collections such as ConcurrentHashMap and CopyOnWriteArrayList provide weakly consistent streams that never throw that exception.
  • Thread safety: streaming a plain ArrayList while another thread writes to it is unsafe.
  • Performance: ArrayList and arrays split efficiently for parallelStream(); LinkedList does not.

6. Collection.stream() vs Related Methods

MethodDefined onModeNotes
stream()CollectionSequentialDefault way to start a pipeline
parallelStream()CollectionPossibly parallelMay still run sequentially; see parallel() vs parallelStream()
Stream.of(...)StreamSequentialFor values written in code
Arrays.stream(arr)ArraysSequentialFor arrays, including primitive arrays
map.entrySet().stream()Map viewSequentialThe usual way to stream a map

7. Common Mistakes and Best Practices

Calling stream() on a Map

Wrong
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():

RemoveIfInsteadOfStream.java
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);
    }
}
Output
[s1:active, s3:active]

Other mistakes to avoid

  • Relying on HashSet or HashMap order. Sort the stream or use a LinkedHash or Tree collection.
  • Calling stream() on a possibly null collection. Return empty collections from methods instead of null.
  • Streaming just to call forEach(). collection.forEach(...) does the same without a stream.

8. Summary

  • stream() is a default method of Collection (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() or values().

9. References