00:00

Collectors in Java 8

Last updated: · Standard (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

CollectorResult
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

GroupingAndJoining.java
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(" | ", "[", "]")));
    }
}
Output
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.

ToMapAndStatistics.java
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());
    }
}
Output
Quantities: {ink=2, pad=1, pen=3}
Without merge function: IllegalStateException
Deliveries: 5, min 28, max 51, average 39.0

4. How groupingBy Works

groupingBy with a downstream collector Each book is assigned a key by the classifier, books with the same key go to the same bucket, and the downstream collector reduces each bucket, for example by counting. Stream<Book> 5 books classifier book -> genre buckets Classic | SciFi downstream counting() -> 2 | 3
Figure 1: groupingBy splits the stream by key; the downstream collector summarises each group.

5. Important Points and Best Practices

  • Always pass a merge function to toMap if keys can repeat.
  • toMap does not accept null values; use another collector if values may be null.
  • Pass a map factory such as TreeMap::new or LinkedHashMap::new when key order matters.
  • partitioningBy always contains both true and false keys, 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 collect terminal operation, added in Java 8.
  • groupingBy and partitioningBy split data; downstream collectors summarise each part.
  • toMap needs a merge function when keys can repeat.
  • joining and summarizingInt produce strings and statistics in one pass.

Related Tutorials

7. References