Custom Collectors in Java Streams
A custom collector is your own implementation of the java.util.stream.Collector<T, A, R> interface (Java 8), used with Stream.collect() when the built-in collectors in Collectors cannot express the result you need. You can write one quickly with the factory method Collector.of() or implement the interface in a class for reuse.
This tutorial explains the four functions every collector is made of, the characteristics that change how it runs, and builds several practical collectors, including one that works correctly in parallel.
1. Syntax and Method Signatures
// java.util.stream.Collector<T, A, R> (Java 8)
Supplier<A> supplier() // creates a new, empty container
BiConsumer<A, T> accumulator() // adds one element to a container
BinaryOperator<A> combiner() // merges two containers (parallel streams)
Function<A, R> finisher() // converts the container into the result
Set<Characteristics> characteristics() // IDENTITY_FINISH, UNORDERED, CONCURRENT
// factory methods (Java 8)
static <T, R> Collector<T, R, R> of(Supplier<R> supplier, BiConsumer<R, T> accumulator,
BinaryOperator<R> combiner, Characteristics... ch)
static <T, A, R> Collector<T, A, R> of(Supplier<A> supplier, BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner, Function<A, R> finisher,
Characteristics... ch)
T is the stream element type, A the mutable accumulation type (often hidden as ?), and R the result.
2. How a Collector Works
Sequentially, collect() calls the supplier once, the accumulator for each element, and the finisher at the end. In parallel, each split part gets its own container from the supplier, and the combiner merges containers pairwise. The container is therefore never shared between threads, so it does not have to be thread-safe.
Characteristics adjust this: IDENTITY_FINISH skips the finisher (the container is the result), UNORDERED says encounter order does not matter, and CONCURRENT says one container may be shared by all threads, which only makes sense with a thread-safe container such as ConcurrentHashMap.
3. Java Examples
Example 1: A collector with Collector.of() (Java 9+)
Collect product names into a single comma-separated string of at most 30 characters, ending with ... if truncated.
import java.util.List;
import java.util.stream.Collector;
public class TruncatingJoin {
static Collector<String, StringBuilder, String> joinUpTo(int max) {
return Collector.of(
StringBuilder::new,
(sb, s) -> sb.append(sb.length() == 0 ? "" : ", ").append(s),
(left, right) -> left.append(left.length() == 0 || right.length() == 0 ? "" : ", ").append(right),
sb -> sb.length() <= max ? sb.toString() : sb.substring(0, max - 3) + "...");
}
public static void main(String[] args) {
List<String> products = List.of("Kettle", "Toaster", "Mixer", "Air fryer", "Blender");
System.out.println(products.stream().limit(2).collect(joinUpTo(30)));
System.out.println(products.stream().collect(joinUpTo(30)));
}
}
Kettle, Toaster Kettle, Toaster, Mixer, Air...
How it works: The supplier creates a StringBuilder, the accumulator appends, the combiner joins two builders for parallel use, and the finisher applies the length limit once, at the end.
Example 2: Statistics that Collectors does not provide (Java 9+)
Compute the median order value with a collector that gathers values and sorts them in the finisher.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collector;
public class MedianCollector {
static Collector<Integer, List<Integer>, Double> median() {
return Collector.of(
ArrayList::new,
List::add,
(a, b) -> { a.addAll(b); return a; },
values -> {
if (values.isEmpty()) return Double.NaN;
Collections.sort(values);
int mid = values.size() / 2;
return values.size() % 2 == 1 ? values.get(mid) : (values.get(mid - 1) + values.get(mid)) / 2.0;
});
}
public static void main(String[] args) {
System.out.println("Median (odd): " + List.of(1200, 350, 980, 4100, 600).stream().collect(median()));
System.out.println("Median (even): " + List.of(10, 40, 20, 30).stream().collect(median()));
System.out.println("Median (none): " + List.<Integer>of().stream().collect(median()));
}
}
Median (odd): 980.0 Median (even): 25.0 Median (none): NaN
How it works: Collectors has averages but no median. The container is a list; the finisher sorts it and picks the middle. The combiner simply appends one list to another, so the collector also works in parallel.
Example 3: A reusable collector class (Java 16+)
Implement Collector in a class that builds a TopN list of the highest-scoring players, keeping memory bounded.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class TopNCollector<T> implements Collector<T, PriorityQueue<T>, List<T>> {
private final int n;
private final Comparator<? super T> order;
TopNCollector(int n, Comparator<? super T> order) {
this.n = n;
this.order = order;
}
@Override public Supplier<PriorityQueue<T>> supplier() { return () -> new PriorityQueue<>(order); }
@Override public BiConsumer<PriorityQueue<T>, T> accumulator() {
return (heap, item) -> {
heap.add(item);
if (heap.size() > n) heap.poll(); // drop the smallest: memory stays at n
};
}
@Override public BinaryOperator<PriorityQueue<T>> combiner() {
return (a, b) -> { b.forEach(item -> accumulator().accept(a, item)); return a; };
}
@Override public Function<PriorityQueue<T>, List<T>> finisher() {
return heap -> {
List<T> result = new ArrayList<>(heap);
result.sort(order.reversed());
return result;
};
}
@Override public Set<Characteristics> characteristics() { return EnumSet.of(Characteristics.UNORDERED); }
record Player(String name, int score) { }
public static void main(String[] args) {
List<Player> players = List.of(new Player("Ana", 820), new Player("Bo", 1340), new Player("Cy", 990),
new Player("Di", 1510), new Player("Ed", 640), new Player("Fa", 1200));
List<Player> top3 = players.parallelStream()
.collect(new TopNCollector<>(3, Comparator.comparingInt(Player::score)));
top3.forEach(p -> System.out.println(p.name() + " " + p.score()));
}
}
Di 1510 Bo 1340 Fa 1200
How it works: A min-heap of size n keeps only the current top three, so memory does not grow with the stream. The collector is UNORDERED because the result does not depend on encounter order, and it runs correctly on a parallel stream.
Example 4: Using a custom collector as a downstream collector (Java 16+)
Find the median delivery time per city by plugging the median collector into groupingBy().
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class MedianPerCity {
record Delivery(String city, int minutes) { }
static Collector<Integer, List<Integer>, Double> median() {
return Collector.of(ArrayList::new, List::add, (a, b) -> { a.addAll(b); return a; },
v -> { Collections.sort(v); int m = v.size() / 2;
return v.size() % 2 == 1 ? v.get(m) : (v.get(m - 1) + v.get(m)) / 2.0; });
}
public static void main(String[] args) {
List<Delivery> deliveries = List.of(
new Delivery("Pune", 34), new Delivery("Pune", 51), new Delivery("Pune", 28),
new Delivery("Goa", 42), new Delivery("Goa", 38));
Map<String, Double> medians = deliveries.stream()
.collect(Collectors.groupingBy(Delivery::city, TreeMap::new,
Collectors.mapping(Delivery::minutes, median())));
System.out.println(medians);
}
}
{Goa=40.0, Pune=34.0}
How it works: A custom collector is a normal Collector, so it composes with groupingBy() and mapping() like any built-in one.
4. Real-World Use Cases
- Statistics: median, percentiles or mode that
Collectorslacks. - Bounded results: top-n lists, samples or capped strings with fixed memory.
- Domain objects: collect order lines directly into an
Invoiceor a report object. - Third-party types: collect into immutable collections of other libraries.
5. Important Points
- Combiner must be correct even if you only use sequential streams; others may call your collector in parallel.
- Containers are not shared unless you declare
CONCURRENT; do not make them thread-safe without reason. IDENTITY_FINISHis applied automatically byCollector.of()when you omit the finisher.- Empty streams: the finisher receives an empty container; handle it.
- Prefer composition first:
collectingAndThen(),teeing()and nested collectors often avoid custom code.
6. Ways to Get a Custom Result
| Approach | Effort | Reusable | Best for |
|---|---|---|---|
Built-in Collectors | None | Yes | Lists, maps, grouping, joining, statistics |
Composition (collectingAndThen, teeing) | Low | Yes | Small adjustments to built-in results |
Collector.of(...) | Low | As a factory method | One-off or small custom collectors |
Class implementing Collector | Medium | Yes | Configurable, documented, tested collectors |
Three-argument collect() | Low | No | Quick custom container without a finisher |
Start with collectingAndThen() and teeing() before writing a collector from scratch.
7. Common Mistakes and Best Practices
A combiner that ignores one side
Collector.of(ArrayList::new, List::add, (a, b) -> a); // drops b: loses data in parallel
The combiner must merge both containers, for example (a, b) -> { a.addAll(b); return a; }.
Declaring CONCURRENT with a non-thread-safe container
With CONCURRENT and UNORDERED, parallel streams share one container across threads. An ArrayList or HashMap then becomes corrupted. Use the characteristic only with concurrent containers.
Other mistakes to avoid
- Doing expensive work in the accumulator that could be done once in the finisher.
- Not handling the empty container in the finisher.
- Writing a collector for something
groupingBy()plus a downstream collector already does.
8. Summary
- A collector is a supplier, an accumulator, a combiner, a finisher and characteristics.
Collector.of()builds one quickly; a class makes it reusable and configurable.- Write a correct combiner, and declare
CONCURRENTonly with thread-safe containers. - Custom collectors compose with
groupingBy()and other collectors.
9. References
Frequently Asked Questions (FAQ)
Q1. How do I create a custom collector in Java?
Use Collector.of(supplier, accumulator, combiner) or Collector.of(supplier, accumulator, combiner, finisher), or implement the Collector interface in a class that returns these four functions and its characteristics.
Q2. What are the four functions of a Collector?
supplier creates a new container, accumulator adds an element to it, combiner merges two containers for parallel streams, and finisher converts the container into the final result.
Q3. Does my collector's container need to be thread-safe?
No, unless you declare the CONCURRENT characteristic. Normally each thread in a parallel stream gets its own container and the combiner merges them.
Q4. What does IDENTITY_FINISH mean?
It means the container itself is the result, so the finisher is the identity function and the stream can skip calling it.
Q5. Can a custom collector be used inside groupingBy()?
Yes. Any Collector can be a downstream collector, so a custom median or top-n collector can compute a result per group.