Collector in Java

Definition

A Collector is an interface introduced in Java 8 that provides a mechanism for collecting elements from a stream into a mutable result container. It is a key component of the Java Stream API, allowing for the transformation of a stream's elements into a different form, such as a collection, a single value, or a map. The Collector interface includes several methods that define its behavior:

  • Supplier: Provides a new container for the result.
  • Accumulator: Incorporates a new element into the result container.
  • Combiner: Merges two result containers.
  • Finisher: Transforms the intermediate result into the final result.
  • Characteristics: Provides additional information about the collector, such as whether it is concurrent or unordered.

Example: Grouping Collector

To illustrate the use of a Collector, consider an example where we want to fold a Stream<String> into a List<List<String>>, simulating the grouping of words on lines of a given maximum length. This can be achieved by defining a generic GroupingCollector.

Generic GroupingCollector

The GroupingCollector class is designed to group elements based on a specified condition. It uses a BiPredicate to determine whether a new element should be added to the current group or start a new group.

import java.util.ArrayList;
import java.util.List;
import java.util.function.*;
import java.util.stream.Collector;

import static java.util.stream.Collector.Characteristics.IDENTITY_FINISH;

public class GroupingCollector<T> {

  private final BiPredicate<List<T>, T> p;

  public GroupingCollector(BiPredicate<List<T>, T> p) {
    this.p = p;
  }

  public void accumulator(List<List<T>> llt, T t) {
    if (! llt.isEmpty()) {
      List<T> last = llt.get(llt.size() - 1);
      if (p.test(last, t)) {
        llt.get(llt.size() - 1).add(t);
      } else {
        addNewList(llt, t);
      }
    } else {
      addNewList(llt, t);
    }
  }

  public List<List<T>> combiner(List<List<T>> list1, List<List<T>> list2) {
    List<List<T>> result = new ArrayList<>();
    result.addAll(list1);
    result.addAll(list2);
    return result;
  }

  public static <T> void addNewList(List<List<T>> llt, T t) {
    List<T> list = new ArrayList<>();
    list.add(t);
    llt.add(list);
  }

  public Collector<T, List<List<T>>, List<List<T>>> collector() {
    return Collector.of(ArrayList::new, this::accumulator, this::combiner, IDENTITY_FINISH);
  }
}

Specific Grouping Collector for Strings

Building on the generic GroupingCollector, a specific implementation for strings can be created. This implementation groups strings based on their cumulative length, ensuring that the total length of strings in a group does not exceed a specified maximum.

import java.util.List;
import java.util.function.BiPredicate;
import java.util.stream.Collector;

public class StringGrouperCollector {

  private StringGrouperCollector() {
  }

  public static Collector<String, List<List<String>>, List<List<String>>> getInstance(int length) {
    BiPredicate<List<String>, String> p = (ls, s) -> length(ls) + s.length() <= length;
    return new GroupingCollector<>(p).collector();
  }

  public static int length(List<String> list) {
    int length = 0;
    for (String s : list) {
      length += s.length();
    }
    return length;
  }
}

This example demonstrates how to create a custom collector that groups strings into lists based on a maximum length constraint. The StringGrouperCollector uses a BiPredicate to evaluate whether a string can be added to the current group or if a new group should be started.