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

The Collector Interface: Anatomy of a Collector

Understand the five methods of Collector<T,A,R>: supplier, accumulator, combiner, finisher, and characteristics.

The Collector Interface: Anatomy of a Collector

What you'll learn: How a Collector<T,A,R> is built from five fundamental methods that define its behavior.

Understanding the Collector Interface

Behind every collector you've used—toList(), groupingBy(), teeing()—lies the Collector interface. This interface defines how stream elements are accumulated into a final result. Understanding its anatomy helps you see what's really happening when you collect.

A Collector<T,A,R> has three type parameters:

  • T: the input element type
  • A: the mutable accumulation type (often hidden from you)
  • R: the final result type

The Five Essential Methods

Every collector is defined by these five methods:

1. supplier()

Creates a new, empty accumulation container. Think of it as getting a fresh bucket to collect items.

2. accumulator()

Adds one element to the accumulation container. This is the "put it in the bucket" operation, called repeatedly as the stream processes elements.

3. combiner()

Merges two partial results. Critical for parallel streams—when multiple threads collect independently, their buckets must be combined.

4. finisher()

Transforms the accumulation container into the final result. Sometimes this is a no-op (the bucket is the result), sometimes it requires conversion.

5. characteristics()

Returns a set of properties describing the collector's behavior (e.g., CONCURRENT, UNORDERED, IDENTITY_FINISH). These guide the stream engine's optimizations.

The Flow

When you call .collect(), the stream framework uses these methods in concert: it creates containers via supplier(), fills them with accumulator(), merges parallel results with combiner(), and produces the final output with finisher().

Key Takeaway: A Collector<T,A,R> is defined by five methods—supplier, accumulator, combiner, finisher, and characteristics—that together orchestrate how stream elements become a final result.