Collectors in Java 8
The Collectors class, added in Java 8, provides ready-made recipes for the collect terminal operation of a stream. With them you can turn a stream into a list, a map, grouped data, a joined string or statistics in a single expression.
This tutorial covers the collectors you will use most often and the parameters that trip people up, such as merge functions and downstream collectors. Each collector also has its own detailed tutorial on this site.
1. Why Are Collectors Needed?
Reducing a stream into a complex result, for example "count the books per genre in alphabetical order", would otherwise require a mutable map and a loop. Collectors package that logic in reusable, composable pieces, and they work correctly with parallel streams.
2. Commonly Used Collectors
| Collector | Result |
|---|---|
toList(), toSet() | a List or Set |
toMap(key, value[, merge[, mapFactory]]) | a Map; the merge function resolves duplicate keys |
groupingBy(classifier[, mapFactory][, downstream]) | Map<K, List<T>> or a downstream result per key |
partitioningBy(predicate[, downstream]) | Map<Boolean, ...> with keys true and false |
joining([delimiter, prefix, suffix]) | a single String |
counting(), averagingInt(), summarizingInt() | numbers and statistics |
3. Practical Examples
Example 1: Grouping, partitioning and joining
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class GroupingAndJoining {
static class Book {
final String title;
final String genre;
final int pages;
Book(String title, String genre, int pages) {
this.title = title;
this.genre = genre;
this.pages = pages;
}
}
public static void main(String[] args) {
List<Book> books = Arrays.asList(
new Book("Dune", "SciFi", 412), new Book("Emma", "Classic", 474),
new Book("Neuromancer", "SciFi", 271), new Book("Persuasion", "Classic", 249),
new Book("Hyperion", "SciFi", 482));
// groupingBy + a downstream collector (TreeMap keeps keys sorted)
Map<String, Long> countByGenre = books.stream()
.collect(Collectors.groupingBy(b -> b.genre, TreeMap::new, Collectors.counting()));
System.out.println("Count by genre : " + countByGenre);
Map<String, Double> avgPages = books.stream()
.collect(Collectors.groupingBy(b -> b.genre, TreeMap::new, Collectors.averagingInt(b -> b.pages)));
System.out.println("Average pages : " + avgPages);
Map<String, String> titles = books.stream()
.collect(Collectors.groupingBy(b -> b.genre, TreeMap::new,
Collectors.mapping(b -> b.title, Collectors.joining(", "))));
System.out.println("Titles : " + titles);
// partitioningBy always creates exactly two groups: true and false
Map<Boolean, List<String>> longBooks = books.stream()
.collect(Collectors.partitioningBy(b -> b.pages > 400,
Collectors.mapping(b -> b.title, Collectors.toList())));
System.out.println("Over 400 pages : " + longBooks.get(true));
System.out.println("Shelf label : " + books.stream().map(b -> b.title)
.collect(Collectors.joining(" | ", "[", "]")));
}
}
Count by genre : {Classic=2, SciFi=3}
Average pages : {Classic=361.5, SciFi=388.3333333333333}
Titles : {Classic=Emma, Persuasion, SciFi=Dune, Neuromancer, Hyperion}
Over 400 pages : [Dune, Emma, Hyperion]
Shelf label : [Dune | Emma | Neuromancer | Persuasion | Hyperion]
The second argument TreeMap::new chooses the map type so the genres print in sorted order. The third argument is a downstream collector that decides what to compute for each group.
Example 2: toMap with duplicates and summary statistics
Without a merge function, toMap throws IllegalStateException on the first duplicate key. With Integer::sum the duplicates are added together.
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class ToMapAndStatistics {
public static void main(String[] args) {
List<String> scans = Arrays.asList("pen", "ink", "pen", "pad", "pen", "ink");
// toMap with a merge function handles duplicate keys
Map<String, Integer> quantity = scans.stream()
.collect(Collectors.toMap(item -> item, item -> 1, Integer::sum, TreeMap::new));
System.out.println("Quantities: " + quantity);
try {
scans.stream().collect(Collectors.toMap(item -> item, item -> 1));
} catch (IllegalStateException e) {
System.out.println("Without merge function: " + e.getClass().getSimpleName());
}
// summarizingInt collects count, sum, min, average and max in one pass
List<Integer> deliveryMinutes = Arrays.asList(32, 45, 28, 51, 39);
IntSummaryStatistics stats = deliveryMinutes.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Deliveries: " + stats.getCount() + ", min " + stats.getMin()
+ ", max " + stats.getMax() + ", average " + stats.getAverage());
}
}
Quantities: {ink=2, pad=1, pen=3}
Without merge function: IllegalStateException
Deliveries: 5, min 28, max 51, average 39.0
4. How groupingBy Works
5. Important Points and Best Practices
- Always pass a merge function to
toMapif keys can repeat. toMapdoes not acceptnullvalues; use another collector if values may be null.- Pass a map factory such as
TreeMap::neworLinkedHashMap::newwhen key order matters. partitioningByalways contains bothtrueandfalsekeys, even if one group is empty.- Java 16 added
Stream.toList(), which returns an unmodifiable list without a collector.
6. Summary
- Collectors are recipes for the
collectterminal operation, added in Java 8. groupingByandpartitioningBysplit data; downstream collectors summarise each part.toMapneeds a merge function when keys can repeat.joiningandsummarizingIntproduce strings and statistics in one pass.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between groupingBy and partitioningBy?
groupingBy creates one group per key returned by a classifier function. partitioningBy always creates exactly two groups, keyed by true and false, based on a predicate.
Q2. Why does Collectors.toMap throw IllegalStateException?
Because two elements produced the same key and no merge function was provided. Pass a third argument such as (a, b) -> a or Integer::sum.
Q3. What is a downstream collector?
A collector passed to groupingBy or partitioningBy that is applied to the elements of each group, for example counting() or mapping(...).
Q4. How do I keep the insertion order of keys?
Use the overload that accepts a map factory and pass LinkedHashMap::new.