Java Stream Collect
What collect Does
collect is the terminal operation that gathers a stream's elements into a container — a List, Set, Map, String, or any other structure — or a summary built from them.
<R, A> R collect(Collector<? super T, A, R> collector)
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)
It's called a mutable reduction. Like reduce, it combines all elements into one result; unlike reduce, it adds elements into a mutable container (an ArrayList, a HashMap, a StringBuilder) instead of creating a new immutable value at every step. That makes it efficient, and it's designed to work correctly in parallel: each thread fills its own container, and the containers are merged at the end.
Most of the time you don't build collectors yourself; you use the ready-made ones from the Collectors class. This lesson covers the collectors that build lists, sets, maps and strings, and how collect works underneath. The next lesson, Collectors Class, covers grouping, partitioning and statistics.
Collecting into Lists, Sets, Arrays and Strings
import java.util.*;
import java.util.stream.*;
public class C1 {
public static void main(String[] args) {
List<String> cities = List.of("Chennai", "Madurai", "Salem", "Chennai", "Trichy");
List<String> a = cities.stream().filter(c -> c.length() > 5).toList();
List<String> b = cities.stream().filter(c -> c.length() > 5).collect(Collectors.toList());
Set<String> unique = cities.stream().collect(Collectors.toSet());
TreeSet<String> sorted = cities.stream().collect(Collectors.toCollection(TreeSet::new));
String joined = cities.stream().distinct().collect(Collectors.joining(", ", "[", "]"));
String[] array = cities.stream().distinct().toArray(String[]::new);
b.add("Erode");
System.out.println("collect(toList) is modifiable: " + b);
try {
a.add("Erode");
} catch (UnsupportedOperationException e) {
System.out.println("toList() is unmodifiable");
}
System.out.println(unique.size() + " unique, sorted " + sorted + ", first " + sorted.first());
System.out.println(joined + " " + array.length);
}
}
Output:
collect(toList) is modifiable: [Chennai, Madurai, Chennai, Trichy, Erode]
toList() is unmodifiable
4 unique, sorted [Chennai, Madurai, Salem, Trichy], first Chennai
[Chennai, Madurai, Salem, Trichy] 4
Three ways to get a list
| Expression | Result | Notes |
|---|---|---|
stream.toList() (Java 16+) | Unmodifiable list | Shortest; the usual choice for results you only read. Allows null elements |
collect(Collectors.toList()) | A modifiable list (currently an ArrayList) | The specification doesn't guarantee the type or mutability — don't rely on either |
collect(Collectors.toUnmodifiableList()) (Java 10+) | Unmodifiable list | Like toList(), but throws NullPointerException on null elements |
collect(Collectors.toCollection(ArrayList::new)) | Exactly an ArrayList | Use when you need a specific, modifiable type |
toList() returning an unmodifiable list is a common surprise when migrating older code: stream.collect(Collectors.toList()) results could be modified, stream.toList() results can't. If you need to add to the result, say so explicitly with toCollection(ArrayList::new).
Other containers
Collectors.toSet()removes duplicates; liketoList(), it gives no guarantee about theSetimplementation or order.Collectors.toCollection(TreeSet::new)collects into exactly the collection you supply — here aTreeSet, which is sorted and offers methods likefirst(). AnyCollectionconstructor reference works:LinkedHashSet::new,ArrayDeque::new,PriorityQueue::new.Collectors.joining(delimiter, prefix, suffix)concatenates strings efficiently with aStringBuilder.joining()andjoining(", ")are the shorter forms. It's the right replacement for string concatenation withreduce.toArray(String[]::new)isn't a collector but serves the same purpose for arrays.
Collecting into Maps with toMap
import java.util.*;
import java.util.stream.*;
public class C2 {
record Product(String sku, String name, double price) { }
public static void main(String[] args) {
List<Product> products = List.of(new Product("PEN-01", "Gel pen", 12.5), new Product("BAG-07", "Laptop bag", 1899),
new Product("INK-03", "Ink", 80), new Product("PEN-01", "Gel pen (new)", 13));
try {
products.stream().collect(Collectors.toMap(Product::sku, Product::name));
} catch (IllegalStateException e) {
System.out.println("IllegalStateException: " + e.getMessage());
}
Map<String, String> latest = products.stream()
.collect(Collectors.toMap(Product::sku, Product::name, (first, second) -> second));
System.out.println(latest.get("PEN-01"));
Map<String, Double> cheapest = products.stream()
.collect(Collectors.toMap(Product::sku, Product::price, Math::min, TreeMap::new));
System.out.println(cheapest);
Map<String, Product> bySku = products.stream()
.collect(Collectors.toMap(Product::sku, p -> p, (x, y) -> x, LinkedHashMap::new));
System.out.println(bySku.keySet());
try {
Stream.of(new Product("X", null, 1)).collect(Collectors.toMap(Product::sku, Product::name));
} catch (NullPointerException e) {
System.out.println("toMap with a null value: NullPointerException");
}
}
}
Output:
IllegalStateException: Duplicate key PEN-01 (attempted merging values Gel pen and Gel pen (new))
Gel pen (new)
{BAG-07=1899.0, INK-03=80.0, PEN-01=12.5}
[PEN-01, BAG-07, INK-03]
toMap with a null value: NullPointerException
Collectors.toMap has three forms:
| Form | Behaviour |
|---|---|
toMap(keyMapper, valueMapper) | Throws IllegalStateException on a duplicate key |
toMap(keyMapper, valueMapper, mergeFunction) | Resolves duplicates with the merge function |
toMap(keyMapper, valueMapper, mergeFunction, mapFactory) | Also chooses the map implementation |
- Duplicate keys are an error by default. The product data contains
PEN-01twice, so the two-argument form fails with a message that names the key and both values. That's deliberate: silently losing data would be worse. If duplicates are possible, you must decide what should happen. - The merge function receives the existing value and the new value for the same key and returns the one to keep — the later one (
(first, second) -> second), the earlier one, the smaller (Math::min), or a combination (a sum, a merged set). - The map factory chooses the implementation:
TreeMap::newfor sorted keys,LinkedHashMap::newto keep the stream's order. Without it, you get aHashMapwith no particular order. - Values can't be
nullintoMap— it throwsNullPointerException. Filter out or replacenullvalues first, or usegroupingBy. Collectors.toUnmodifiableMap(...)(Java 10+) builds an immutable map, with the same rules.
The Three-Argument collect
collect(supplier, accumulator, combiner) builds a container without a Collector object:
import java.util.*;
import java.util.stream.*;
public class C3 {
public static void main(String[] args) {
ArrayList<String> list = Stream.of("b", "a", "c").collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
System.out.println(list);
StringBuilder sb = Stream.of("Java", "is", "fun")
.collect(StringBuilder::new, (acc, s) -> acc.append(s).append(' '), StringBuilder::append);
System.out.println("[" + sb.toString().strip() + "]");
BitSet evens = IntStream.range(0, 20).filter(n -> n % 2 == 0)
.collect(BitSet::new, BitSet::set, BitSet::or);
System.out.println(evens + " cardinality " + evens.cardinality());
}
}
Output:
[b, a, c]
[Java is fun]
{0, 2, 4, 6, 8, 10, 12, 14, 16, 18} cardinality 10
| Argument | Role | ArrayList example |
|---|---|---|
| supplier | Creates a new, empty container | ArrayList::new |
| accumulator | Adds one element to a container | ArrayList::add |
| combiner | Merges two containers (used in parallel) | ArrayList::addAll |
In parallel, each thread gets its own container from the supplier, fills it with the accumulator, and the combiner merges the partial containers — no locking and no shared mutable state. This is exactly why collect is safe in parallel where adding to a shared list from forEach isn't (Stream API lesson). The form is useful for containers that have no ready-made collector, such as BitSet — and for primitive streams (IntStream has no collect(Collector) method, only this form).
Practical Example: Building Lookup Indexes and an Export
Applications often load a list of records once and then need fast lookups by different keys, plus an export. One pass of collect per structure builds each of them.
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.*;
public class Index {
record Product(String sku, String name, String category, BigDecimal price, Set<String> tags) { }
static String csvField(String s) {
return s.contains(",") || s.contains("\"") ? "\"" + s.replace("\"", "\"\"") + "\"" : s;
}
public static void main(String[] args) {
List<Product> catalog = List.of(
new Product("PEN-01", "Gel pen", "stationery", new BigDecimal("12.50"), Set.of("office", "school")),
new Product("BAG-07", "Laptop bag, 15\"", "bags", new BigDecimal("1899.00"), Set.of("travel", "office")),
new Product("INK-03", "Ink refill", "stationery", new BigDecimal("80.00"), Set.of("office")),
new Product("PCK-11", "Daypack", "bags", new BigDecimal("1299.00"), Set.of("travel", "school")));
Map<String, Product> bySku = catalog.stream()
.collect(Collectors.toUnmodifiableMap(Product::sku, Function.identity()));
Map<String, Set<String>> skusByTag = catalog.stream()
.flatMap(p -> p.tags().stream().map(tag -> Map.entry(tag, p.sku())))
.collect(Collectors.toMap(Map.Entry::getKey,
e -> new TreeSet<>(Set.of(e.getValue())),
(s1, s2) -> { s1.addAll(s2); return s1; },
TreeMap::new));
Set<String> categories = catalog.stream().map(Product::category).collect(Collectors.toCollection(TreeSet::new));
String csv = catalog.stream()
.map(p -> String.join(",", p.sku(), csvField(p.name()), p.category(), p.price().toPlainString()))
.collect(Collectors.joining("\n", "sku,name,category,price\n", "\n"));
System.out.println("lookup INK-03: " + bySku.get("INK-03").name());
System.out.println("tags: " + skusByTag);
System.out.println("categories: " + categories);
System.out.print(csv);
}
}
Output:
lookup INK-03: Ink refill
tags: {office=[BAG-07, INK-03, PEN-01], school=[PCK-11, PEN-01], travel=[BAG-07, PCK-11]}
categories: [bags, stationery]
sku,name,category,price
PEN-01,Gel pen,stationery,12.50
BAG-07,"Laptop bag, 15""",bags,1899.00
INK-03,Ink refill,stationery,80.00
PCK-11,Daypack,bags,1299.00
How each structure is built:
- A primary index:
toUnmodifiableMap(Product::sku, Function.identity())maps each SKU to its product, so lookups are a singlegetinstead of a search.Function.identity()means "the element itself". The two-argument form is used on purpose: duplicate SKUs would indicate corrupt data and should fail loudly. - An inverted index (tag → SKUs):
flatMapturns each product into(tag, sku)pairs —Map.entrycreates a small immutable pair.toMapthen groups them: the value for each new key is aTreeSetwith one SKU, and the merge function adds the SKUs of duplicate keys into the existing set. ATreeMapkeeps tags sorted. (The Collectors Class lesson shows a shorter version withgroupingByandmapping.) - Distinct sorted categories:
toCollection(TreeSet::new). - A CSV export: each product becomes one line (with the CSV escaping from the Write Files lesson for the name containing a comma and a quote), and
joiningadds the delimiter, a header line as the prefix, and a trailing newline as the suffix.
All four structures are built from the same immutable source list without modifying it, and each would work unchanged with parallelStream().