Collector.Characteristics: Optimization Hints
You'll learn how Collector characteristics tell the Stream API what optimizations are safe to apply during collection.
What Are Collector Characteristics?
When you create a custom collector using the Collector interface, you can specify characteristics that describe special properties of your collector. These are optimization hints that tell the Stream framework how it can safely speed up the collection process. Think of them like labels on a package: "Fragile," "This Side Up," or "Can Be Stacked"—they guide how the package should be handled.
The three main characteristics are defined in the Collector.Characteristics enum:
CONCURRENT
Signals that the collector's accumulator can be called concurrently from multiple threads on the same result container. This is rare and requires thread-safe containers. Without this, parallel streams must use separate containers per thread and then combine them.
UNORDERED
Indicates that the collection operation doesn't depend on encounter order. For example, collecting to a Set doesn't care about order, so this characteristic allows further optimizations when the stream is unordered.
IDENTITY_FINISH
Means the finisher function is the identity function—it just returns the accumulator unchanged. The framework can skip calling the finisher entirely, saving an operation. Most simple collectors like toList() have this characteristic.
How They Enable Optimizations
When you call Collector.of() to create a custom collector, the last parameter is a set of these characteristics. The Stream API reads these hints and chooses faster execution paths. For instance, a CONCURRENT collector in a parallel stream can avoid creating intermediate containers.
Key Takeaway: Collector characteristics are optimization flags (CONCURRENT, UNORDERED, IDENTITY_FINISH) that inform the Stream API about safe shortcuts it can take when executing your collector.