CKTIS / Java
Collector.of: build a custom collector with four functions
Define a stream collector that creates working state, adds elements, merges partial results, and converts the state into a final value.
Version: Java SE 21
Syntax
import java.util.stream.Collector;
// Static overloads declared by java.util.stream.Collector:
static <T, A, R> Collector<T, A, R> of(
Supplier<A> supplier, BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner, Function<A, R> finisher,
Collector.Characteristics... characteristics);
static <T, R> Collector<T, R, R> of(
Supplier<R> supplier, BiConsumer<R, T> accumulator,
BinaryOperator<R> combiner,
Collector.Characteristics... characteristics);Collector.of is a static factory method on the java.util.stream.Collector interface. It builds a collector you pass to the terminal operation Stream.collect(collector). In Collector<T, A, R>, T is the input element type, A is the mutable intermediate state type, and R is the final result type.
In the four-function overload, the supplier creates a fresh, empty A container on each call; the accumulator updates it with one T and returns nothing; the combiner merges two partial results and returns the combined A; and the finisher converts the final A into R. Optional Collector.Characteristics flags follow the functions. Both overloads throw NullPointerException if an argument is null.
A parallel reduction can fill separate containers and then merge them. Reducing the input in parts and merging them must yield a result equivalent to reducing the input without splitting it. For an UNORDERED collector, results that differ only in order can still be equivalent. Merging an empty container into the right-hand side of a partial result must leave an equivalent result. Do not return a shared mutable container from the supplier, and do not set CONCURRENT unless the accumulator can safely update the same container from multiple threads at once.
The three-function overload takes no finisher: it returns Collector<T, R, R> and automatically sets IDENTITY_FINISH. This is a flag, not a method named Collector.identityFinish; it lets the reduction skip the finisher. Do not set it when the finisher performs a necessary transformation. If you only need to concatenate text in encounter order, use the built-in Collectors.joining instead.
Examples
import java.util.List;
import java.util.stream.Collector;
public class Main {
record Totals(long count, long totalLength) {}
public static void main(String[] args) {
Collector<String, long[], Totals> lengthTotals = Collector.of(
() -> new long[2],
(state, word) -> {
state[0]++;
state[1] += word.length();
},
(left, right) -> {
left[0] += right[0];
left[1] += right[1];
return left;
},
state -> new Totals(state[0], state[1])
);
Totals totals = List.of("ant", "bear", "ox")
.parallelStream()
.collect(lengthTotals);
System.out.println("count=" + totals.count()
+ ", totalLength=" + totals.totalLength());
}
}Result
count=3, totalLength=9
The `long[]` stores the number of strings and the sum of their `String.length()` values. The `combiner` adds the corresponding slots, and the `finisher` creates a `Totals` record. Both a parallel and a sequential stream produce `count=3, totalLength=9` for this input.
Related lessons
- Java · Lesson 45 · Intermediate · Version: 2