Collector Interface
The Collector interface in Java is a powerful tool for performing reduction operations on streams. It provides a structured way to summarize elements in a stream, enabling operations such as grouping, partitioning, and reducing. The interface acts as a blueprint for implementing these reduction operations, defining a contract for custom collectors.
Overview
The Collector interface can be seen as a domain-specific language (DSL) for aggregating data. It allows for collecting, grouping, and partitioning items in a Stream. The Collectors class offers static factory methods to create various Collector objects, supporting multilevel grouping and other complex operations.
Methods of the Collector Interface
The Collector interface declares five essential methods:
-
Supplier: The
suppliermethod returns aSupplierof an empty accumulator, which serves as the starting point for the collection process. -
Accumulator: The
accumulatormethod is aBiConsumerthat takes an accumulator and an element from the stream, incorporating the element into the result. -
Combiner: The
combinermethod is aBinaryOperatorthat merges two accumulators. This is particularly useful in parallel processing to combine results from different substreams. -
Finisher: The
finishermethod returns a function that transforms the accumulator into the final result. Often, it returns the identity function if no transformation is needed. -
Characteristics: The
characteristicsmethod returns an immutable set ofCharacteristics, defining the behavior of the collector, such as whether it can be used in parallel.
Collector Interface Signature
Below is the signature of the Collector interface, which includes the five methods mentioned:
Listing 6.4. The Collector interface
public interface Collector<T, A, R> {
Supplier<A> supplier();
BiConsumer<A, T> accumulator();
Function<A, R> finisher();
BinaryOperator<A> combiner();
Set<Characteristics> characteristics();
}
Example: PrimeNumbersCollector
An example of a custom collector is the PrimeNumbersCollector, which partitions numbers into prime and non-prime categories. This collector implements the Collector interface and provides specific implementations for each of the five methods.
Listing 6.7. The PrimeNumbersCollector
public class PrimeNumbersCollector
implements Collector<Integer,
Map<Boolean, List<Integer>>,
Map<Boolean, List<Integer>>> {
@Override
public Supplier<Map<Boolean, List<Integer>>> supplier() {
return () -> new HashMap<Boolean, List<Integer>>() {{
put(true, new ArrayList<Integer>());
put(false, new ArrayList<Integer>());
}};
}
@Override
public BiConsumer<Map<Boolean, List<Integer>>, Integer> accumulator() {
return (Map<Boolean, List<Integer>> acc, Integer candidate) -> {
acc.get(isPrime(acc.get(true), candidate)).add(candidate);
};
}
@Override
public BinaryOperator<Map<Boolean, List<Integer>>> combiner() {
return (Map<Boolean, List<Integer>> map1, Map<Boolean, List<Integer>> map2) -> {
map1.get(true).addAll(map2.get(true));
map1.get(false).addAll(map2.get(false));
return map1;
};
}
@Override
public Function<Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH));
}
}
Implementing a ToListCollector
Another example of a custom collector is the ToListCollector<T>, which gathers all elements of a Stream<T> into a List<T>. This collector uses the same object for both the accumulation process and the final result.
public class ToListCollector<T> implements Collector<T, List<T>, List<T>>
In summary, the Collector interface provides a flexible and powerful way to define custom reduction operations on streams, allowing developers to implement complex data aggregation logic efficiently.
FAQ (Frequently asked questions)
What is the purpose of the Collector interface in Java?
What operations can be performed using the Collector interface?
What does the Collector interface provide in Java?
What methods are declared in the Collector interface?
How many methods does the Collector interface declare?
What is the role of the supplier method in the Collector interface?
What does the finisher method do in the Collector interface?
What is the purpose of the combiner method in the Collector interface?
What does the characteristics method return in the Collector interface?
What is the contract defined by the Collector interface in Java?
How does the PrimeNumbersCollector implement the Collector interface?
What is the role of the supplier method in PrimeNumbersCollector?
How does the accumulator method work in PrimeNumbersCollector?
What does the combiner method do in PrimeNumbersCollector?
What is the finisher method in PrimeNumbersCollector?
What characteristics does the PrimeNumbersCollector have?
How can the Collector interface be used as a DSL?
What does the Collectors class provide?