Implementing Custom Java Collectors with Collector.of
Learn how Java collectors work inside: the supplier, accumulator, combiner and finisher functions, the IDENTITY_FINISH, UNORDERED and CONCURRENT characteristics, building collectors with Collector.of, wrapping a downstream collector and the parallel bugs a bad combiner causes.
kvi5hnuCode Sprout team member9 min readOn this page
The Collectors class has a collector for most jobs, but sometimes you want your own. Maybe you need a result type that no factory produces, or a collector that does something special with each element. Writing one is easy once you understand the four functions every collector is made of. This article also explains the rules a collector must follow so that it gives the right answer on parallel streams.
The four functions
While collecting, a collector puts the elements into an internal data structure called the result container. Each collector chooses its own container type. A sequential stream fills one container. A parallel stream fills several containers at once, one per chunk of the stream, and then merges them. At the end, the collector may turn the final container into a different result object.
A Collector<T, A, R>, where T is the element type, A the container type and R the result type, provides four functions for these steps:
| Method | Function type | Job |
|---|---|---|
supplier() | Supplier<A> | creates a new, empty result container |
accumulator() | BiConsumer<A, T> | adds one element to a container |
combiner() | BinaryOperator<A> | merges two containers into one (used by parallel streams) |
finisher() | Function<A, R> | turns the final container into the result |
For a list collector:
- The supplier is
ArrayList::new. - The accumulator is
List::add. The container is the accumulator's first parameter, which is why a method reference such asList::addfits so neatly. - The combiner appends the right list to the left one:
(left, right) -> { left.addAll(right); return left; }. - The finisher does nothing, since the
ArrayListalready is the result. That's the most common case.

For parallel streams, the combiner merges adjacent chunks, the left one first. That's how a list collector keeps the encounter order even when it runs in parallel.
Characteristics
A collector also reports a set of characteristics, flags that let the stream skip work:
IDENTITY_FINISH: the finisher is the identity function, so the stream can return the container unchanged and needn't call it.UNORDERED: the result doesn't depend on the order in which elements arrive, as with a set.CONCURRENT: the accumulator may be called on the same container from several threads at once, because the container is thread-safe. If the collector is alsoUNORDERED(or the stream is unordered), a parallel stream uses one shared container and skips combining.
Collectors.joining() has none of these flags. Its container is a StringBuilder, which needs a finisher to become a String, isn't thread-safe and depends on order. toConcurrentMap has all three: a thread-safe ConcurrentHashMap that needs no finishing and doesn't care about order.
Building a collector with Collector.of
You don't need a class that implements Collector. Pass the functions to Collector.of:
static <T> Collector<T, ?, List<T>> toArrayList() {
return Collector.of(
ArrayList<T>::new,
List::add,
(left, right) -> { left.addAll(right); return left; },
Collector.Characteristics.IDENTITY_FINISH);
}
There are two overloads:
Collector.of(supplier, accumulator, combiner, characteristics...)has no finisher. The container is the result, andIDENTITY_FINISHis added automatically.Collector.of(supplier, accumulator, combiner, finisher, characteristics...)includes a finisher.
The finisher is handy when the container is a mutable helper but the result should be something nicer. The demo accumulates the count, minimum and maximum of string lengths in an int[], then the finisher wraps them in a record:
record LengthStats(int count, int shortest, int longest) {}
static Collector<String, int[], LengthStats> lengthStats() {
return Collector.of(
() -> new int[] { 0, Integer.MAX_VALUE, Integer.MIN_VALUE },
(a, s) -> { a[0]++; a[1] = Math.min(a[1], s.length()); a[2] = Math.max(a[2], s.length()); },
(a, b) -> { a[0] += b[0]; a[1] = Math.min(a[1], b[1]); a[2] = Math.max(a[2], b[2]); return a; },
a -> new LengthStats(a[0], a[1], a[2]));
}
A custom collector works anywhere a predefined one does, including as a downstream collector: partitioningBy(w -> w.contains("e"), lengthStats()).
A sampling collector with a downstream collector
Here's a collector that keeps each element with probability p, a simple form of statistical sampling. It's almost toArrayList, except that the accumulator adds only some elements:
static <T> Collector<T, List<T>, List<T>> sampling(double p) {
return Collector.of(ArrayList<T>::new,
(container, e) -> { if (Math.random() < p) container.add(e); },
(left, right) -> { left.addAll(right); return left; },
Function.identity(),
Collector.Characteristics.IDENTITY_FINISH);
}
Following the style of the Collectors API, a second version should let callers choose what happens to the accepted elements with a downstream collector. The new collector reuses the downstream's supplier, combiner, finisher and characteristics, and wraps only its accumulator:
static <T, A, R> Collector<T, A, R> sampling(double p, Collector<T, A, R> downstream) {
BiConsumer<A, T> downstreamAccumulator = downstream.accumulator();
return Collector.of(downstream.supplier(),
(container, e) -> { if (Math.random() < p) downstreamAccumulator.accept(container, e); },
downstream.combiner(),
downstream.finisher(),
downstream.characteristics().toArray(Collector.Characteristics[]::new));
}
One wrinkle: characteristics() returns a Set, while Collector.of takes a varargs array, hence the toArray(Collector.Characteristics[]::new). Note also that the accumulator is fetched once, outside the lambda. Calling downstream.accumulator() for every element would work but wastes time.
The demo uses a Random with a fixed seed instead of Math.random(), so its output is the same on every run. In a parallel stream, a shared generator would make the sample depend on thread timing. That's fine for real sampling, which is random anyway, but a shared Random becomes a point of contention between threads. ThreadLocalRandom.current() avoids that.
The rules for a correct collector
A collector must produce the same result whether the stream runs sequentially or in parallel. That works only if:
- The supplier returns a new container each time. Returning one shared container breaks everything.
- The combiner really merges. Its result must include the elements of both arguments. A combiner that returns
leftand ignoresrightlooks harmless, because sequential streams never call it, but in parallel it silently loses elements. The demo shows exactly that. - The accumulator and combiner are associative. Splitting the input differently must not change the result.
- Containers aren't shared between threads, unless the collector declares
CONCURRENTand the container is thread-safe.
To test a collector, always run it on a parallel stream of a few thousand elements and compare the result with the sequential one.
A complete example
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Solution {
// a collector that behaves like toList(), built from four functions
static <T> Collector<T, ?, List<T>> toArrayList() {
return Collector.of(
ArrayList<T>::new, // supplier: a new result container
List::add, // accumulator: add one element
(left, right) -> { left.addAll(right); return left; }, // combiner: merge two containers
Collector.Characteristics.IDENTITY_FINISH); // the container is the result
}
// keeps each element with probability p, using a seeded generator for repeatable output
static <T> Collector<T, List<T>, List<T>> sampling(double p, long seed) {
var generator = new Random(seed);
return Collector.of(ArrayList<T>::new,
(container, e) -> { if (generator.nextDouble() < p) container.add(e); },
(left, right) -> { left.addAll(right); return left; },
Function.identity(),
Collector.Characteristics.IDENTITY_FINISH);
}
// the same, but with any downstream collector for the accepted elements
static <T, A, R> Collector<T, A, R> sampling(double p, long seed, Collector<T, A, R> downstream) {
var generator = new Random(seed);
BiConsumer<A, T> downstreamAccumulator = downstream.accumulator();
return Collector.of(downstream.supplier(),
(container, e) -> { if (generator.nextDouble() < p) downstreamAccumulator.accept(container, e); },
downstream.combiner(),
downstream.finisher(),
downstream.characteristics().toArray(Collector.Characteristics[]::new));
}
record LengthStats(int count, int shortest, int longest) {}
// a mutable container plus a finisher that turns it into an immutable record
static Collector<String, int[], LengthStats> lengthStats() {
return Collector.of(
() -> new int[] { 0, Integer.MAX_VALUE, Integer.MIN_VALUE },
(a, s) -> { a[0]++; a[1] = Math.min(a[1], s.length()); a[2] = Math.max(a[2], s.length()); },
(a, b) -> { a[0] += b[0]; a[1] = Math.min(a[1], b[1]); a[2] = Math.max(a[2], b[2]); return a; },
a -> new LengthStats(a[0], a[1], a[2]));
}
public static void main(String[] args) {
List<String> words = List.of("stream", "collector", "map", "reduce", "gatherer", "filter", "of");
System.out.println("toArrayList: " + words.stream().collect(toArrayList()));
System.out.println("parallel toArrayList keeps order: "
+ words.parallelStream().collect(toArrayList()).equals(words));
System.out.println("sampled: " + IntStream.range(1, 100).boxed().collect(sampling(0.1, 42)));
System.out.println("sampled into a TreeSet: "
+ IntStream.range(1, 100).boxed().collect(sampling(0.1, 42, Collectors.toCollection(TreeSet::new))));
System.out.println("sampled count: " + IntStream.range(1, 100).boxed().collect(sampling(0.1, 42, Collectors.counting())));
System.out.println("length stats: " + words.stream().collect(lengthStats()));
System.out.println("as a downstream collector: " + words.stream()
.collect(Collectors.partitioningBy(w -> w.contains("e"), lengthStats())));
// a combiner that ignores its second argument only fails in parallel
Collector<Integer, List<Integer>, List<Integer>> broken = Collector.of(
ArrayList::new, List::add, (left, _) -> left);
System.out.println("broken combiner, sequential size: "
+ IntStream.range(0, 1000).boxed().collect(broken).size());
System.out.println("broken combiner, parallel loses elements: "
+ (IntStream.range(0, 1000).boxed().parallel().collect(broken).size() < 1000));
// characteristics of some predefined collectors
System.out.println("toList: " + Collectors.toList().characteristics());
System.out.println("toSet: " + Collectors.toSet().characteristics());
System.out.println("joining: " + Collectors.joining().characteristics());
System.out.println("toConcurrentMap: "
+ Collectors.toConcurrentMap(Function.identity(), Function.identity()).characteristics());
}
}
toArrayList: [stream, collector, map, reduce, gatherer, filter, of]
parallel toArrayList keeps order: true
sampled: [25, 72, 73, 84, 93, 98, 99]
sampled into a TreeSet: [25, 72, 73, 84, 93, 98, 99]
sampled count: 7
length stats: LengthStats[count=7, shortest=2, longest=9]
as a downstream collector: {false=LengthStats[count=2, shortest=2, longest=3], true=LengthStats[count=5, shortest=6, longest=9]}
broken combiner, sequential size: 1000
broken combiner, parallel loses elements: true
toList: [IDENTITY_FINISH]
toSet: [UNORDERED, IDENTITY_FINISH]
joining: []
toConcurrentMap: [CONCURRENT, UNORDERED, IDENTITY_FINISH]
Common questions
When should I write a collector rather than use reduce or a gatherer?
Write a collector when the result has a shape no factory method produces and you build it in a mutable container, especially if you want to reuse it as a downstream collector of groupingBy. Use reduce for combining immutable values with an associative operation, and a gatherer when the logic is an intermediate step or depends on element order and position.
Can I implement Collector as a regular class?
Yes. Implement the five methods supplier, accumulator, combiner, finisher and characteristics. Collector.of is simply shorter for most cases. A class is useful when the collector has configuration fields or you want to give it a name in stack traces.
What happens if I declare IDENTITY_FINISH but my finisher does something?
The stream trusts the flag, skips the finisher and casts the container to the result type. You get a ClassCastException, or a silently unfinished result. Declare IDENTITY_FINISH only when the container is the result, and let Collector.of add it automatically by using the overload without a finisher.
Is CONCURRENT always faster in parallel?
No. A single shared container avoids the merge step, but all threads then compete for it. For containers with cheap merges, separate containers per chunk are often faster. Measure both.
How do I test a custom collector? Run it on the same data sequentially and in parallel, on empty input and on a single element, and compare the results. A few thousand elements in a parallel stream are enough to exercise the combiner.
API reference
java.util.stream.Collector<T, A, R>
| Method | Description |
|---|---|
Supplier<A> supplier() | creates a new result container |
BiConsumer<A, T> accumulator() | adds an element to a result container |
BinaryOperator<A> combiner() | combines two result containers into one |
Function<A, R> finisher() | turns the final container into the result |
Set<Collector.Characteristics> characteristics() | the collector's characteristics |
static Collector<T, R, R> of(Supplier<R> supplier, BiConsumer<R, T> accumulator, BinaryOperator<R> combiner, Characteristics... characteristics) | a collector whose container is the result (IDENTITY_FINISH) |
static Collector<T, A, R> of(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner, Function<A, R> finisher, Characteristics... characteristics) | a collector with the given functions and characteristics |
java.util.stream.Collector.Characteristics (enum)
| Constant | Meaning |
|---|---|
IDENTITY_FINISH | the finisher is the identity and can be skipped |
UNORDERED | the result doesn't depend on encounter order |
CONCURRENT | the accumulator can be called from several threads on one container |
Summary
- A collector consists of a supplier (new container), an accumulator (add element), a combiner (merge containers) and a finisher (final result).
- Parallel streams fill one container per chunk and combine adjacent containers, which keeps encounter order.
- Characteristics (
IDENTITY_FINISH,UNORDERED,CONCURRENT) let the stream skip finishing, ordering or combining. Collector.ofbuilds a collector from lambdas. Wrap a downstream collector by reusing its functions and adapting its accumulator.- A wrong combiner or a shared container shows up only in parallel, so test collectors on parallel streams. Position-dependent work belongs in a gatherer.
Practice Questions
When does a stream call a collector's combiner?
Only when the stream runs in parallel and has filled more than one container. Then the combiner merges the containers of adjacent chunks. A sequential stream uses a single container and never calls the combiner, which is why combiner bugs go unnoticed in sequential tests.
Write a collector that collects strings into a StringBuilder, separated by spaces, and returns a String.
Collector.of(StringBuilder::new, (sb, s) -> { if (!sb.isEmpty()) sb.append(' '); sb.append(s); }, (a, b) -> { if (!a.isEmpty() && !b.isEmpty()) a.append(' '); return a.append(b); }, StringBuilder::toString). It needs a finisher, so it isn't IDENTITY_FINISH. In practice, Collectors.joining(" ") does the same job.
What's wrong with this supplier: var list = new ArrayList<T>(); return Collector.of(() -> list, List::add, ...)?
Every call of the supplier returns the same list. In parallel, several threads add to one non-thread-safe ArrayList at once, and the combiner then merges the list with itself, duplicating elements. Even sequentially, reusing the collector piles up results from earlier runs. The supplier must create a new container each time: ArrayList::new.
Why does Collectors.toSet() report UNORDERED while toList() doesn't?
The result of toSet() is a set, which has no order, so the order in which elements arrive doesn't matter. A list records the encounter order of its elements, so toList() must preserve it.
Why is "keep every third element" a poor fit for a collector?
On a parallel stream, each container sees only its own chunk and doesn't know the elements' positions in the whole stream, so it can't tell which elements are every third one. The collector API offers no way to demand sequential, ordered processing. A gatherer, which can be declared sequential, handles this cleanly.
Previous: Java Downstream Collectors: counting, mapping, filtering, teeing and More
Next: Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect
Related reading
- Java Downstream Collectors: counting, mapping, filtering, teeing and More
- Java groupingBy and partitioningBy: Grouping Stream Elements
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.