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:

  1. Supplier: The supplier method returns a Supplier of an empty accumulator, which serves as the starting point for the collection process.

  2. Accumulator: The accumulator method is a BiConsumer that takes an accumulator and an element from the stream, incorporating the element into the result.

  3. Combiner: The combiner method is a BinaryOperator that merges two accumulators. This is particularly useful in parallel processing to combine results from different substreams.

  4. Finisher: The finisher method returns a function that transforms the accumulator into the final result. Often, it returns the identity function if no transformation is needed.

  5. Characteristics: The characteristics method returns an immutable set of Characteristics, 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)