Skip to lesson

collect and the Collectors class

collect is the terminal operation that pours the elements of a stream into a container, such as a list, a set or a map. The container is decided by a collector, a ready-made recipe that you pick from the Collectors class.

What collect does and what a collector is

A Collector describes how to gather stream elements into a result, such as a List, Set, Map or String; the Collectors class provides the common ones.

Before streams, building a set of unique cities meant the same three steps every time: create a HashSet, loop over the orders, and call add for each city. Every program wrote that loop again.

Example 1 · The loop way and the collect way

UniqueCitiesDemo.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.stream.Collectors;
public class UniqueCitiesDemo {    public static void main(String[] args) {        List<String> orderCities = List.of("Pune", "Delhi", "Pune", "Chennai", "Delhi", "Pune");
        // old way: create, loop, add        Set<String> loopSet = new HashSet<>();        for (String city : orderCities) {            loopSet.add(city);        }
        // new way: one collect call        Set<String> streamSet = orderCities.stream().collect(Collectors.toSet());
        System.out.println("Orders: " + orderCities.size());        System.out.println("Unique cities (loop): " + loopSet.size());        System.out.println("Unique cities (stream): " + streamSet.size());        System.out.println("Same contents: " + loopSet.equals(streamSet));        System.out.println("Ships to Chennai: " + streamSet.contains("Chennai"));
        // what a collector does, written out by hand: create, add, join        List<String> manual = orderCities.stream()                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);        System.out.println("Hand-made collect: " + manual);    }}
Output
Orders: 6
Unique cities (loop): 3
Unique cities (stream): 3
Same contents: true
Ships to Chennai: true
Hand-made collect: [Pune, Delhi, Pune, Chennai, Delhi, Pune]

What this code does

  • The loop and collect(Collectors.toSet()) build equal sets: three unique cities out of six orders. The stream version states the goal, not the steps.
  • The three-argument collect shows what any collector holds inside: ArrayList::new creates the container, ArrayList::add adds one element, ArrayList::addAll joins two containers in parallel runs. Collectors methods package these parts for you.
  • Why collect: the loop spells out how to fill the set; collect says what you want. Changing to a list or a map later is a one-word change, not a rewrite of the loop.

collect hides the loop. You say what container you want, and the stream does the creating and adding. A collector is an object that knows four things: how to create an empty container, how to add one element to it, how to join two containers, and how to finish the result. The joining step is only used when a stream runs in parallel. Collectors (with an s) is a class in java.util.stream full of static methods that return ready-made collectors: toSet(), toCollection(...), toMap(...), groupingBy(...) and many more. This whole module is about them.

Order of execution

What a collector does

Put the parts of a collector in the order they are used.

collect is a terminal operation: after it runs, the stream is used up, exactly like count or forEach.

toSet and toUnmodifiableSet

Collectors.toSet() puts the elements into a set, so duplicates are dropped. Today it gives a HashSet, but the documentation promises nothing about the type, the order or whether you may change it later. Never print it and expect a fixed order.

Example 2 · toSet versus toUnmodifiableSet

CouponCodesDemo.javaJava
import java.util.List;import java.util.Set;import java.util.TreeSet;import java.util.stream.Collectors;
public class CouponCodesDemo {    public static void main(String[] args) {        List<String> entered = List.of("SAVE10", "FEST50", "SAVE10", "NEW20");
        Set<String> editable = entered.stream().collect(Collectors.toSet());        editable.add("BONUS5");        System.out.println("Editable set size: " + editable.size());        System.out.println("Sorted view: " + new TreeSet<>(editable));
        Set<String> allowed = entered.stream().collect(Collectors.toUnmodifiableSet());        System.out.println("Allowed codes: " + allowed.size());        try {            allowed.add("HACK99");        } catch (UnsupportedOperationException e) {            System.out.println("Cannot add to a read-only set");        }    }}
Output
Editable set size: 4
Sorted view: [BONUS5, FEST50, NEW20, SAVE10]
Allowed codes: 3
Cannot add to a read-only set

What this code does

  • Both collectors drop the repeated SAVE10, so each set starts with 3 codes. The toSet() result can take a fourth code; the program prints it through a TreeSet because a HashSet has no fixed order.
  • toUnmodifiableSet() returns a read-only set, so add throws UnsupportedOperationException. Use it for answers that must not change after they are built.

Collectors.toUnmodifiableSet() (Java 10) gives a read-only set. Calling add or remove on it throws UnsupportedOperationException. Duplicates in the stream are fine: they are simply dropped. A null element is not fine: it throws NullPointerException.

  • toSet(): unique elements, no promised order, usually a HashSet you can change.
  • toUnmodifiableSet(): unique elements, read-only, rejects null.
  • Use the read-only version when the set is a final answer that nobody should edit, such as the set of allowed coupon codes.

toCollection: you choose the exact type

Collectors.toCollection(supplier) takes a supplier, a function that creates a new empty collection. You usually pass a constructor reference such as TreeSet::new, so the stream fills exactly the collection you asked for.

Example 3 · toCollection: sorted, first-seen and reversed sets

ChosenSetDemo.javaJava
import java.util.Comparator;import java.util.LinkedHashSet;import java.util.List;import java.util.TreeSet;import java.util.stream.Collectors;
public class ChosenSetDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(78, 92, 65, 92, 78, 88);
        TreeSet<Integer> sorted = marks.stream()                .collect(Collectors.toCollection(TreeSet::new));        System.out.println("Sorted unique marks: " + sorted);        System.out.println("Lowest: " + sorted.first() + ", highest: " + sorted.last());
        List<String> upiPayees = List.of("Ravi", "Bookstore", "Ravi", "Metro", "Bookstore");        LinkedHashSet<String> firstSeen = upiPayees.stream()                .collect(Collectors.toCollection(LinkedHashSet::new));        System.out.println("Payees in first-paid order: " + firstSeen);
        TreeSet<Integer> highFirst = marks.stream()                .collect(Collectors.toCollection(() -> new TreeSet<Integer>(Comparator.reverseOrder())));        System.out.println("Unique marks, high first: " + highFirst);    }}
Output
Sorted unique marks: [65, 78, 88, 92]
Lowest: 65, highest: 92
Payees in first-paid order: [Ravi, Bookstore, Metro]
Unique marks, high first: [92, 88, 78, 65]

What this code does

  • toCollection(TreeSet::new) returns a real TreeSet, so the result is sorted and you can call first() and last() on it. The variable type can be TreeSet<Integer>, not just Set.
  • LinkedHashSet::new keeps the order in which each payee first appeared. A lambda supplier lets you build a TreeSet with any comparator, here highest first. It says new TreeSet<Integer> because reverseOrder() gives Java too little to guess the type from <>.

toCollection(TreeSet::new) gives unique values in sorted order. toCollection(LinkedHashSet::new) gives unique values in the order they first appeared. toCollection(ArrayList::new) gives a list you are sure you can change. For a custom order, pass a lambda: toCollection(() -> new TreeSet<Integer>(Comparator.reverseOrder())). Write the element type inside TreeSet<Integer> here: with the empty <>, Java cannot work out the type and the line does not compile.

Choosing the result type

Ask two questions. Do duplicates matter? Does the order matter? Then pick the smallest tool that answers both.

Example 4 · Choosing between toList, toSet and toCollection

AttendanceDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.TreeSet;import java.util.stream.Collectors;
public class AttendanceDemo {    public static void main(String[] args) {        // one entry per class attended this week        List<String> entries = List.of("Asha", "Vikram", "Asha", "Neha", "Vikram", "Asha");
        List<String> log = entries.stream().toList();        System.out.println("Full log (" + log.size() + "): " + log);
        TreeSet<String> present = entries.stream()                .collect(Collectors.toCollection(TreeSet::new));        System.out.println("Students present at least once: " + present);
        ArrayList<String> roll = entries.stream()                .distinct()                .collect(Collectors.toCollection(ArrayList::new));        roll.add("Imran");          // a late admission, allowed        roll.sort(null);        System.out.println("Editable roll: " + roll);
        try {            log.add("Imran");        } catch (UnsupportedOperationException e) {            System.out.println("toList() result is read-only");        }    }}
Output
Full log (6): [Asha, Vikram, Asha, Neha, Vikram, Asha]
Students present at least once: [Asha, Neha, Vikram]
Editable roll: [Asha, Imran, Neha, Vikram]
toList() result is read-only

What this code does

  • The attendance log must keep every entry, so toList() fits. The set of students present only cares about who, not how often, so a TreeSet fits and prints in name order.
  • When you plan to add or sort later, toCollection(ArrayList::new) promises a real ArrayList. The toList() result is read-only, so add on it throws.

Example 5 · Trap: null and the read-only collectors

NullSetDemo.javaJava
import java.util.Arrays;import java.util.List;import java.util.Objects;import java.util.Set;import java.util.stream.Collectors;
public class NullSetDemo {    public static void main(String[] args) {        // a form where one student left the city blank        List<String> cities = Arrays.asList("Pune", null, "Goa");
        Set<String> normal = cities.stream().collect(Collectors.toSet());        System.out.println("toSet keeps null: " + normal.contains(null));
        try {            cities.stream().collect(Collectors.toUnmodifiableSet());        } catch (NullPointerException e) {            System.out.println("toUnmodifiableSet rejects null");        }
        Set<String> clean = cities.stream()                .filter(Objects::nonNull)                .collect(Collectors.toUnmodifiableSet());        System.out.println("After filtering: " + clean.size() + " cities");    }}
Output
toSet keeps null: true
toUnmodifiableSet rejects null
After filtering: 2 cities

What this code does

  • toSet() quietly stores a null, which can crash later code that calls a method on each city. toUnmodifiableSet() fails at once with NullPointerException.
  • The fix is to remove blanks before collecting with filter(Objects::nonNull). Objects.nonNull(x) returns true when x is not null. Real form data often has missing values, so filter first.
  • Keep every element in stream order, read-only: toList() (Java 16).
  • Remove duplicates, order does not matter: collect(Collectors.toSet()).
  • Remove duplicates and sort, or keep first-seen order: toCollection(TreeSet::new) or toCollection(LinkedHashSet::new).
  • Need to add or sort later: toCollection(ArrayList::new), which promises a real ArrayList.
A TreeSet treats two elements as duplicates when its comparator says they are equal, so the comparator decides what "unique" means.

Next step

Check your understanding

11 quick questions