java.util.stream · java.base · since Java 1.8

Collectors

declaration
public final class Collectors

The standard Collector recipes: containers (toList/toSet/toMap), strings (joining), statistics, and the grouping/partitioning family with composable downstreams.

Key methods

static Collector toList() / toSet() / toUnmodifiableList()Container terminals.
static Collector toMap(keyFn, valueFn[, mergeFn])Throws on duplicate keys without a merge function!
static Collector groupingBy(classifier[, downstream])SQL GROUP BY — Map<K, List<T>> or aggregated.
static Collector partitioningBy(predicate[, downstream])Boolean split, both keys guaranteed.
static Collector joining(delim, prefix, suffix)Delimited strings.
static Collector counting() / summingInt(…) / averagingDouble(…)Downstream aggregates.
static Collector mapping(fn, downstream) / filtering(p, downstream)Adapt elements before a downstream.
static Collector teeing(c1, c2, merger)Two collectors, one pass (Java 12).

Example

Java
Map<String, Long> byDept = staff.stream()
        .collect(groupingBy(Employee::dept, counting()));