Course contentsShow
← Java
Lesson 1622 of 2,87034. Collectors in DepthFree lesson

Custom Collector Example: Immutable Collection

Build a custom collector that accumulates elements into an immutable collection, demonstrating all components.

Custom Collector Example: Immutable Collection

You'll learn how to build a complete custom collector that accumulates elements into an immutable collection, putting together all five Collector components you've studied.

The Goal

Imagine you want to collect stream elements into an immutable list—one that can't be modified after creation. You've used toUnmodifiableList(), but let's build our own to understand how collectors really work under the hood.

Building the Custom Collector

You'll use Collector.of() with all five components:

import java.util.*;
import java.util.function.*;
import java.util.stream.Collector;

public static <T> Collector<T, ?, List<T>> toImmutableList() {
    // 1. Supplier: creates mutable container for accumulation
    Supplier<List<T>> supplier = ArrayList::new;
    
    // 2. Accumulator: adds each element to the container
    BiConsumer<List<T>, T> accumulator = List::add;
    
    // 3. Combiner: merges two containers (for parallel streams)
    BinaryOperator<List<T>> combiner = (list1, list2) -> {
        list1.addAll(list2);
        return list1;
    };
    
    // 4. Finisher: converts mutable list to immutable
    Function<List<T>, List<T>> finisher = Collections::unmodifiableList;
    
    // 5. Characteristics: none (not IDENTITY_FINISH or CONCURRENT)
    return Collector.of(supplier, accumulator, combiner, finisher);
}

Using Your Custom Collector

List<String> immutableNames = Stream.of("Alice", "Bob", "Charlie")
    .collect(toImmutableList());

// immutableNames.add("Dave"); // throws UnsupportedOperationException

Why Each Component Matters

During collection, elements are added to a mutable ArrayList (efficient). The finisher wraps that list in an unmodifiable view at the very end. The combiner handles merging partial results if the stream runs in parallel.

Key Takeaway:
A custom collector for immutable collections uses a mutable accumulator for efficiency, then transforms it to immutable in the finisher—demonstrating how all five Collector components work together in practice.