00:00

Stream vs Collection in Java

Last updated:

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

AspectCollectionStream
Main purposeStore and manage elementsCompute a result from elements
StorageHolds all elements in memoryHolds nothing; pulls from a source
EvaluationEager: elements exist before you use themLazy: elements are computed when the terminal operation needs them
TraversalAny number of timesOnce; a second terminal operation throws IllegalStateException
SizeFiniteFinite or infinite (iterate(), generate())
Modificationadd(), remove(), removeIf()Not possible; operations return new streams or results
Iteration styleExternal (for-each, Iterator)Internal (the library runs the loop)
ParallelismYour own threadsparallel() or parallelStream()
Element accesslist.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.

Collection compared with Stream Left panel, Collection: stores every element in memory, computes elements before they are added, can be traversed many times and supports add and remove. Right panel, Stream: stores nothing, computes elements on demand, can be traversed once and never changes its source. Collection (stores data) elements live in memory values computed before adding traverse as often as you like add(), remove(), clear() Stream (processes data) no storage: reads a source values computed on demand consumed by one terminal operation never changes the source VS
Figure 1: A collection is a container you can revisit and change; a stream is a single pass over a source that produces a result.

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.

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

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

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

CollectionConversions.java
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");
    }
}
Output
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 Map for 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 HashSet has no defined order, so sort it if the output order matters.
  • Unmodifiable results: Stream.toList() returns an unmodifiable list; use toCollection(ArrayList::new) when you must edit it.
  • Duplicates: a List keeps them, a Set removes them; in a stream use distinct().
  • Thread safety: neither an ArrayList nor 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:

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

StoreTheCollection.java
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);
    }
}
Output
Count: 3
Names: [NISHA, ARJUN, LEELA]

Other mistakes to avoid

  • Collecting just to count. list.stream().filter(...).toList().size() builds a list for nothing; use count().
  • Using a stream for a single lookup by index. list.get(3) is clearer and faster than skip(3).findFirst().
  • Streaming a collection to change it. Use removeIf(), replaceAll() or a new collection, not side effects in forEach().

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, and toList() or a collector to go back.

8. References