Java Stream Collect

Su Suriya Ravichandran Updated 18 Nov 2026
7 min read ·Lesson 177 of 306

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

ExpressionResultNotes
stream.toList() (Java 16+)Unmodifiable listShortest; 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 listLike toList(), but throws NullPointerException on null elements
collect(Collectors.toCollection(ArrayList::new))Exactly an ArrayListUse 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; like toList(), it gives no guarantee about the Set implementation or order.
  • Collectors.toCollection(TreeSet::new) collects into exactly the collection you supply — here a TreeSet, which is sorted and offers methods like first(). Any Collection constructor reference works: LinkedHashSet::new, ArrayDeque::new, PriorityQueue::new.
  • Collectors.joining(delimiter, prefix, suffix) concatenates strings efficiently with a StringBuilder. joining() and joining(", ") are the shorter forms. It's the right replacement for string concatenation with reduce.
  • 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:

FormBehaviour
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-01 twice, 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::new for sorted keys, LinkedHashMap::new to keep the stream's order. Without it, you get a HashMap with no particular order.
  • Values can't be null in toMap — it throws NullPointerException. Filter out or replace null values first, or use groupingBy.
  • 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
ArgumentRoleArrayList example
supplierCreates a new, empty containerArrayList::new
accumulatorAdds one element to a containerArrayList::add
combinerMerges 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:

  1. A primary index: toUnmodifiableMap(Product::sku, Function.identity()) maps each SKU to its product, so lookups are a single get instead 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.
  2. An inverted index (tag → SKUs): flatMap turns each product into (tag, sku) pairs — Map.entry creates a small immutable pair. toMap then groups them: the value for each new key is a TreeSet with one SKU, and the merge function adds the SKUs of duplicate keys into the existing set. A TreeMap keeps tags sorted. (The Collectors Class lesson shows a shorter version with groupingBy and mapping.)
  3. Distinct sorted categories: toCollection(TreeSet::new).
  4. 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 joining adds 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().

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Stream Collect and get answers drawn from it.

Signed-in readers only.