Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series — Extended Java Programming Java Tutorial Module 18 - Modern Java Features 8 to 21

Java 8 Stream collect with Collectors toList toMap joining

Reviewed & accurate
AI Summary

Introduction

The Stream.collect terminal operation and the Collectors factory class were introduced in Java 8 released in March 2014 as part of JSR 335 "Lambda Expressions and Virtual Extension Methods". The operation is the bridge between the lazy functional pipeline of Stream.map, Stream.filter, and Stream.sorted, and the eager mutable collections like List, Map, and Set that the rest of the program consumes. Without collect, the result of a stream would be only iterable or reducible; with collect, the result is a regular collection that downstream code can index, modify, or serialize.

For a Java learner, Stream collect with Collectors is the most-used terminal operation in real-world Java code. The three collectors named in the title, Collectors.toList, Collectors.toMap, and Collectors.joining, cover the three most common collection goals: produce a list of all stream elements, produce a map keyed by a stream element property, and produce a joined string of all stream elements. This post demonstrates each, plus the related collectors Collectors.groupingBy, Collectors.partitioningBy, and Collectors.collectingAndThen that compose on top of the three basics.

What is Java 8 Stream collect with Collectors?

The collect operation is a terminal operation on Stream that materializes the stream elements into a mutable result container. It belongs to the family of mutable reduction operations, distinct from the immutable reduction of Stream.reduce that produces a single value by repeated application of a BinaryOperator. The collect operation accepts a Collector, which is a recipe composed of four parts: a supplier that creates the result container, an accumulator that adds an element to the container, a combiner that merges two containers (used in parallel streams), and a finisher that performs a final transformation on the container.

The Collectors utility class in java.util.stream provides ready-made Collector instances for the most common collection patterns. Collectors.toList returns a Collector that builds an ArrayList. Collectors.toMap returns a Collector that builds a HashMap, keyed by a function applied to each element. Collectors.joining returns a Collector that builds a String by appending each element with an optional delimiter, prefix, and suffix. Each collector hides the supplier-accumulator-combiner-finisher mechanics behind a single factory call.

The collect operation differs from forEach and reduce in that it produces a mutable container rather than a single value or a side effect. forEach discards the result; reduce combines elements into one value by repeated application of a binary operator; collect accumulates elements into a growing container. The collect operation is preferred over manual for-loop collection because it composes with the rest of the stream pipeline, is parallelizable, and is less verbose than the equivalent manual code.

How Stream collect with Collectors Works - Step by Step

Step 1: Build a stream pipeline. Start with Stream.of, List.stream, or any of the JDK stream factories. Apply intermediate operations like map, filter, sorted, distinct, or limit to transform the stream. The intermediate operations are lazy; they run only when the terminal operation is invoked.

Step 2: Pick the right Collector for the desired output. Collectors.toList for a List of stream elements. Collectors.toMap for a Map keyed by a property of each element. Collectors.joining for a single String of all elements concatenated with optional delimiters. Collectors.toSet for a Set. Collectors.toCollection for a specific collection type. Collectors.groupingBy for a Map keyed by a property where each value is a List of elements with that key.

Step 3: Configure the Collector with lambdas or method references. Collectors.toMap takes a key-extraction function and a value-extraction function, and optionally a merge function that resolves collisions when two stream elements produce the same key. Collectors.joining takes an optional delimiter, prefix, and suffix. Collectors.groupingBy takes a classifier function that produces the key for each element.

Step 4: Invoke collect with the configured Collector. The collect operation pulls the stream through the intermediate operations, runs the supplier to create the result container, runs the accumulator to add each element to the container, runs the combiner to merge containers from parallel sub-streams, and runs the finisher to transform the container to the final result.

Step 5: Consume the result. The result is a regular collection or value: a List, a Map, a Set, or a String. Downstream code can iterate it, index it, serialize it, or pass it to other APIs. To preserve immutability, wrap the result with Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList) or use Collectors.toUnmodifiableList in Java 10 or later.

Java Program for Java 8 Stream collect

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamCollectDemo {

    static class Person {
        String name;
        int age;
        String city;
        Person(String name, int age, String city) {
            this.name = name; this.age = age; this.city = city;
        }
        public String getName() { return name; }
        public int getAge() { return age; }
        public String getCity() { return city; }
        @Override public String toString() {
            return name + "(" + age + "@" + city + ")";
        }
    }

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30, "NYC"),
            new Person("Bob", 25, "LA"),
            new Person("Carol", 35, "NYC"),
            new Person("Dave", 28, "LA"),
            new Person("Eve", 30, "SF")
        );

        System.out.println("--- (1) Collectors.toList ---");
        List<String> names = people.stream()
            .map(Person::getName)
            .collect(Collectors.toList());
        System.out.println("  names = " + names);

        // toList with a filter
        List<String> nycNames = people.stream()
            .filter(p -> p.getCity().equals("NYC"))
            .map(Person::getName)
            .collect(Collectors.toList());
        System.out.println("  NYC names = " + nycNames);

        System.out.println();
        System.out.println("--- (2) Collectors.toMap ---");
        // Key=name, value=age
        Map<String, Integer> ageByName = people.stream()
            .collect(Collectors.toMap(Person::getName, Person::getAge));
        System.out.println("  ageByName = " + ageByName);

        // Collisions handled by a merge function (keep the larger value)
        Map<String, Integer> countByCity = people.stream()
            .collect(Collectors.toMap(
                Person::getCity,           // key extractor
                p -> 1,                    // value extractor
                (a, b) -> a + b            // merge function on key collision
            ));
        System.out.println("  countByCity = " + countByCity);

        // Force a specific Map implementation with the four-arg overload
        Map<String, Integer> sortedAge = people.stream()
            .collect(Collectors.toMap(
                Person::getName,
                Person::getAge,
                (a, b) -> a,                                 // no collisions expected
                () -> new TreeMap<>()                           // explicit map factory
            ));
        System.out.println("  sortedAgeByName (TreeMap) = " + sortedAge);

        System.out.println();
        System.out.println("--- (3) Collectors.joining ---");
        // Plain joining: concatenate with no delimiter
        String joined = people.stream()
            .map(Person::getName)
            .collect(Collectors.joining());
        System.out.println("  joined (no delimiter) = " + joined);

        // Joining with delimiter
        String csv = people.stream()
            .map(Person::getName)
            .collect(Collectors.joining(", "));
        System.out.println("  csv = " + csv);

        // Joining with delimiter, prefix, and suffix
        String bracketed = people.stream()
            .map(Person::getName)
            .collect(Collectors.joining(", ", "[", "]"));
        System.out.println("  bracketed = " + bracketed);

        System.out.println();
        System.out.println("--- (4) Collectors.groupingBy ---");
        // Group people by city
        Map<String, List<Person>> byCity = people.stream()
            .collect(Collectors.groupingBy(Person::getCity));
        System.out.println("  byCity = " + byCity);

        // Two-level grouping: city then age-bucket
        Map<String, Map<String, List<Person>>> byCityAndAge = people.stream()
            .collect(Collectors.groupingBy(
                Person::getCity,
                Collectors.groupingBy(p -> p.getAge() >= 30 ? "old" : "young")
            ));
        System.out.println("  byCityAndAge = " + byCityAndAge);

        // groupingBy with a downstream collector other than toList
        Map<String, Long> countByCityGroup = people.stream()
            .collect(Collectors.groupingBy(
                Person::getCity,
                Collectors.counting()
            ));
        System.out.println("  countByCityGroup = " + countByCityGroup);

        // Average age per city
        Map<String, Double> avgAgeByCity = people.stream()
            .collect(Collectors.groupingBy(
                Person::getCity,
                Collectors.averagingInt(Person::getAge)
            ));
        System.out.println("  avgAgeByCity = " + avgAgeByCity);

        System.out.println();
        System.out.println("--- (5) Collectors.partitioningBy ---");
        // Partition into two groups by a boolean predicate
        Map<Boolean, List<Person>> byAge30 = people.stream()
            .collect(Collectors.partitioningBy(p -> p.getAge() >= 30));
        System.out.println("  age >= 30: " + byAge30.get(true));
        System.out.println("  age <  30: " + byAge30.get(false));

        System.out.println();
        System.out.println("--- (6) Collectors.collectingAndThen ---");
        // Wrap toList with an unmodifiable wrapper
        List<String> immutable = people.stream()
            .map(Person::getName)
            .collect(Collectors.collectingAndThen(
                Collectors.toList(),
                Collections::unmodifiableList
            ));
        System.out.println("  immutable names = " + immutable);
        try {
            immutable.add("Hacker");
        } catch (UnsupportedOperationException e) {
            System.out.println("  add rejected: " + e.getClass().getSimpleName());
        }

        // computingAndThen to extract a single max element
        String oldestName = people.stream()
            .collect(Collectors.collectingAndThen(
                Collectors.maxBy(Comparator.comparingInt(Person::getAge)),
                opt -> opt.map(Person::getName).orElse("(none)")
            ));
        System.out.println("  oldest name = " + oldestName);

        System.out.println();
        System.out.println("--- (7) Three-argument collect: supplier + accumulator + combiner ---");
        // The low-level form, equivalent to Collectors.toList
        List<String> manual = Stream.of("a", "b", "c")
            .collect(
                () -> new ArrayList<>(),               // supplier
                (list, s) -> list.add(s),                // accumulator
                (list1, list2) -> list1.addAll(list2)   // combiner
            );
        System.out.println("  manual collect = " + manual);

        // Parallel stream uses the combiner to merge partial containers
        List<String> parallel = people.parallelStream()
            .map(Person::getName)
            .collect(Collectors.toList());
        System.out.println("  parallelStream names = " + parallel);
    }
}

Code Explanation - Line by Line

Section (1) shows Collectors.toList, the simplest collector. It produces an ArrayList whose elements are the stream output in encounter order. The collector is the terminal operation that pulls the lazy map and filter stages through to actual execution. Without collect, the map and filter calls would be queued but never executed. The second example filters people to NYC residents before mapping to names, demonstrating that collect composes with the rest of the pipeline.

Section (2) shows Collectors.toMap in three configurations. The two-argument form takes a key extractor and a value extractor; the result is a HashMap. The three-argument form adds a merge function that resolves what to do when two stream elements produce the same key; the example uses (a, b) -> a + b to count people per city, where the value is initially 1 for each element and collisions add them up. The four-argument form adds a supplier that produces the result map; using () -> new TreeMap<>() forces the result to be a TreeMap, which keeps keys sorted.

Section (3) shows Collectors.joining in three configurations. The no-argument form concatenates with no delimiter, which is rarely useful but demonstrates the baseline. The one-argument form adds a delimiter, which produces CSV-style output. The three-argument form adds a prefix and a suffix, which is useful for producing array literals like [a, b, c] for logging or JSON-like output.

Section (4) shows Collectors.groupingBy, the most powerful collector. The one-argument form groups elements by a classifier function, producing a Map from key to List of elements. The two-argument form adds a downstream collector that decides how to combine the elements with the same key; passing Collectors.counting produces a count per key instead of a list, and passing Collectors.averagingInt produces an average per key. The example also shows two-level grouping where the downstream collector is itself a groupingBy, producing a Map of Maps that nests the secondary grouping.

Section (5) shows Collectors.partitioningBy, a special case of groupingBy where the classifier is a boolean predicate. The result is a Map<Boolean, List<T>> with exactly two entries: true for elements that match the predicate and false for those that do not. Partitioning is faster than grouping for boolean classifiers because the map has only two keys.

Section (6) shows Collectors.collectingAndThen, which wraps another collector and applies a finisher function to the result. The first example wraps toList with Collections::unmodifiableList to produce an immutable list. The second example wraps Collectors.maxBy with a function that extracts the name from the resulting Optional, demonstrating how to flatten an Optional-typed collector result into a plain value.

Section (7) shows the three-argument form of collect, which is the low-level API that Collectors.toList wraps. The supplier creates the result container (an ArrayList), the accumulator adds an element to it, and the combiner merges two containers (used for parallel streams). The parallel stream example demonstrates that the combiner is invoked to merge partial results from different threads; the final list order may differ from the sequential encounter order.

Sample Input and Output

--- (1) Collectors.toList ---
  names = [Alice, Bob, Carol, Dave, Eve]
  NYC names = [Alice, Carol]
--- (2) Collectors.toMap ---
  ageByName = {Bob=25, Alice=30, Carol=35, Eve=30, Dave=28}
  countByCity = {NYC=2, LA=2, SF=1}
  sortedAgeByName (TreeMap) = {Alice=30, Bob=25, Carol=35, Dave=28, Eve=30}
--- (3) Collectors.joining ---
  joined (no delimiter) = AliceBobCarolDaveEve
  csv = Alice, Bob, Carol, Dave, Eve
  bracketed = [Alice, Bob, Carol, Dave, Eve]
--- (4) Collectors.groupingBy ---
  byCity = {NYC=[Alice(30@NYC), Carol(35@NYC)], LA=[Bob(25@LA), Dave(28@LA)], SF=[Eve(30@SF)]}
  byCityAndAge = {NYC={young=[Alice(30@NYC)], old=[Carol(35@NYC)]}, LA={young=[Bob(25@LA), Dave(28@LA)]}, SF={young=[Eve(30@SF)]}}
  countByCityGroup = {NYC=2, LA=2, SF=1}
  avgAgeByCity = {NYC=32.5, LA=26.5, SF=30.0}
--- (5) Collectors.partitioningBy ---
  age >= 30: [Alice(30@NYC), Carol(35@NYC), Eve(30@SF)]
  age <  30: [Bob(25@LA), Dave(28@LA)]
--- (6) Collectors.collectingAndThen ---
  immutable names = [Alice, Bob, Carol, Dave, Eve]
  add rejected: UnsupportedOperationException
  oldest name = Carol
--- (7) Three-argument collect: supplier + accumulator + combiner ---
  manual collect = [a, b, c]
  parallelStream names = [Alice, Bob, Carol, Dave, Eve]

The output confirms every collector behavior. toList produces a list of the stream output. toMap produces a map keyed by the chosen property, with collisions handled by the merge function. joining concatenates with optional delimiter, prefix, and suffix. groupingBy groups elements by a classifier with optional downstream collector. partitioningBy splits into two groups by a boolean predicate. collectingAndThen wraps another collector with a finisher function. The three-argument form shows the low-level supplier-accumulator-combiner API that all collectors build on.

Common Mistakes to Avoid

The first mistake is calling Collectors.toMap without a merge function when the stream may produce duplicate keys. Without a merge function, two stream elements that produce the same key cause an IllegalStateException with the message "Duplicate key" at runtime, which is hard to debug because the error does not appear until the duplicate is encountered. Always pass a merge function if duplicates are possible, even if you only intend to keep one of the values.

The second mistake is using Collectors.toList and expecting a specific List implementation. The collector returns a List backed by an ArrayList in current JDK versions, but the Javadoc explicitly does not guarantee the implementation. If you need a specific type like LinkedList or CopyOnWriteArrayList, use Collectors.toCollection(LinkedList::new) instead. The third mistake is mutating the result of Collectors.toList and assuming it is thread-safe; it is a regular ArrayList, not synchronized, so concurrent modification throws ConcurrentModificationException.

The fourth mistake is using collect on an infinite stream. The operation is terminal and pulls the entire stream through, so it never terminates on an infinite source. Use Stream.limit to bound the stream first. The fifth mistake is using the three-argument collect form without a combiner when parallel streams are involved; the combiner is what merges partial containers from different threads, and without it the result is corrupted.

The sixth mistake is using Collectors.joining on a stream of non-String values without first mapping to String. The collector requires CharSequence elements, so a stream of Integer or custom objects requires a .map(Object::toString) before joining. Finally, do not assume the order of toMap or groupingBy results is the same as the stream encounter order; HashMap does not preserve order, so use TreeMap or LinkedHashMap (via the four-arg toMap or two-arg groupingBy with a map factory) when order matters.

Real-World Applications

Stream collect with Collectors powers the entire Java 8 data-processing API surface. Spring Data JPA repository methods return Stream<T>, which callers collect into List or Map for REST responses. Spring Boot REST controllers use Collectors.toList in @GetMapping methods to convert entity streams to DTO lists. The Spring Batch framework uses collect in item processors to materialize chunks of stream-processed items.

In the JDK, Collectors.toList is the most common terminal operation, used everywhere from java.util.stream.IntStream.range to Collectors.toMap for building caches. The Collectors.groupingBy is the foundation of the JDK's group-by-and-aggregate pattern, used in java.util.stream.Collectors itself for its own downstream combinators. In Reactor, the Flux.collectList and Flux.collectMap operators are the reactive analogues of Collectors.toList and Collectors.toMap. In Apache Camel, the multicast and aggregate EIPs use collector-style APIs. Studying this post gives you the tools to write declarative data-transformation pipelines that are concise, parallelizable, and compositional, and to recognize the mutable-reduction pattern in every modern Java framework.

Conclusion

We demonstrated Collectors.toList, Collectors.toMap, Collectors.joining, Collectors.groupingBy, Collectors.partitioningBy, and Collectors.collectingAndThen, plus the low-level three-argument collect form. The collect operation is the bridge between the lazy functional stream pipeline and the eager mutable collections that the rest of the program consumes, and the Collectors class is the standard recipe library for the most common collection goals. With this post and the previous Java 8 posts on Optional, default methods, static interface methods, method references, and functional interfaces, you have the complete Java 8 functional toolkit: the types, the syntax, the target types, and the terminal operations that bring it all together.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments