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

collectingAndThen: Post-Processing Collected Results

Apply a finishing transformation to collected results using collectingAndThen, such as wrapping in unmodifiable collections.

collectingAndThen: Post-Processing Collected Results

What you'll learn: How to apply a final transformation to the result of a collector using collectingAndThen.

The Core Idea

Sometimes you collect data into a structure, but you want to perform one last transformation before returning the final result. The collectingAndThen collector lets you wrap another collector and apply a finishing function to its output. Think of it like a gift-wrapping station at a store: you've already packaged the items (collected them), but now you want to add a final bow or seal (transform the collection).

How It Works

The collectingAndThen method takes two arguments:

  1. A downstream collector that does the actual collecting
  2. A finisher function that transforms the collected result
Collector<T,A,R> collectingAndThen(
    Collector<T,A,RR> downstream,
    Function<RR,R> finisher
)

Common Use Case: Unmodifiable Collections

The most common use is wrapping collections to make them immutable:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

List<String> unmodifiable = names.stream()
    .filter(n -> n.length() > 3)
    .collect(collectingAndThen(
        toList(),
        Collections::unmodifiableList
    ));

// unmodifiable.add("Dave"); // Would throw UnsupportedOperationException

Here, toList() collects the elements, then Collections::unmodifiableList wraps the result to prevent modifications.

Other Transformations

You can apply any finishing transformation: getting the size, extracting a specific element, or converting to another type entirely. The power is in separating the collection logic from the final post-processing step.

Key Takeaway: collectingAndThen allows you to apply a finishing transformation to any collected result, commonly used to wrap collections as unmodifiable or perform final computations on the collected data.