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

Collector.of: Building Custom Collectors

Use Collector.of() factory method to create custom collectors by providing the five required functions.

Collector.of: Building Custom Collectors

You'll learn how to create your own custom collectors using the Collector.of() factory method by assembling the five essential functions.

The Factory Method for Custom Collectors

Instead of implementing the Collector interface directly, Java provides Collector.of() as a convenient factory method. You supply the five functions you've just learned about—supplier, accumulator, combiner, finisher, and characteristics—and Collector.of() assembles them into a working collector.

Think of Collector.of() as a collector builder: you bring the individual pieces (the five functions), and it snaps them together into a complete, usable collector.

The Two Overloads

There are two versions of Collector.of():

  1. With explicit finisher: Collector.of(supplier, accumulator, combiner, finisher, characteristics...)
  2. Without finisher (identity finisher): Collector.of(supplier, accumulator, combiner, characteristics...)

The second form assumes your accumulator container is already in the desired final form, so no transformation is needed.

Simple Example: Collecting to a StringBuilder

Collector<String, StringBuilder, String> customJoiner = 
    Collector.of(
        StringBuilder::new,                  // supplier
        StringBuilder::append,               // accumulator
        StringBuilder::append,               // combiner
        StringBuilder::toString              // finisher
    );

String result = Stream.of("Java", "is", "powerful")
    .collect(customJoiner);
// result: "Javaispowerful"

Here you create a collector that accumulates strings into a StringBuilder and finishes by converting to a String.

Characteristics Matter

You can add characteristics as trailing arguments:

Collector.of(supplier, accumulator, combiner, finisher, 
    Collector.Characteristics.UNORDERED)

Key Takeaway: Collector.of() is the practical way to build custom collectors by providing the supplier, accumulator, combiner, finisher, and optional characteristics—no need to implement the interface manually.