Finisher: Transforming the Accumulator to Final Result
What you'll learn: How the finisher function converts a mutable accumulator into the final, often immutable, result type that your collector returns.
The Final Transformation Step
You've seen how a collector uses a supplier to create a container, an accumulator to add elements, and a combiner to merge partial results. But what if the mutable container you've been building isn't the type you actually want to return?
The finisher is the fourth component of the Collector interface. It's a Function that takes your mutable accumulator and transforms it into the final result type.
Why Finishers Matter
Think of the finisher like wrapping a gift after you've assembled it. You've built something in a mutable workspace (the accumulator), but now you want to present it in its final form—often immutable or in a different structure altogether.
For example:
- You accumulated elements into an
ArrayList, but want to return an immutable list - You built a
StringBuilder, but need to return aString - You collected items in a temporary collection, but want to convert it to an array
When Is the Finisher Called?
The finisher executes once per collection operation, after all accumulation and combining is complete. It's the last step before your collect() terminal operation returns a value.
Some collectors have "identity finishers"—they simply return the accumulator unchanged. For instance, Collectors.toList() directly returns the ArrayList it built, so its finisher does nothing.
Key Takeaway: The finisher is your collector's final opportunity to transform the mutable accumulator into the desired result type, enabling you to return immutable or differently-typed results from the collection process.