Java SE API

Collectors.toCollection()

Accumulates values in a collection supplied by the factory, in encounter order. Java SE API; example uses Java 21-compatible syntax.

Formal Syntax & Structure

java syntaxjava
static <T,C extends Collection<T>> Collector<T,?,C> toCollection(Supplier<C> collectionFactory)

Parameters & Attributes

NameTypeDescription
collectionFactorySupplier<C>Creates a new empty collection

Return Value

Collector<T,?,C>

Accumulates values in a collection supplied by the factory, in encounter order.

Working Example

Example Snippetjava
import java.util.*;import java.util.stream.*;public class Main {    public static void main(String[] args) {        record Person(String team, String name) {}        var people = List.of(new Person("red", "Ada"), new Person("red", "Bo"), new Person("blue", "Cy"));        var labels = people.stream().collect(Collectors.groupingBy(Person::team, TreeMap::new, Collectors.mapping(Person::name, Collectors.joining(" / "))));        System.out.println(labels);        var mutable = people.stream().map(Person::name).collect(Collectors.toCollection(ArrayList::new));        mutable.add("Dee");        System.out.println(mutable);    }}
Java Reference