Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.collect()

Gathers stream elements into a collection, a string or another structure.

Available since: Java 8

Syntax

<R, A> R collect(Collector<? super T, A, R> collector)

Parameters

ParameterTypeDescription
collectorCollector<? super T, A, R>How to gather the result, usually from the `Collectors` class.

Return value

RThe collector's result: a list, set, map, string or number.

Examples

Different collectors:

void main() {
    List<String> words = List.of("java", "stream", "api", "java");
    Set<String> unique = words.stream().collect(Collectors.toCollection(TreeSet::new));
    String joined = words.stream().collect(Collectors.joining(", "));
    Map<Integer, Long> byLength = words.stream()
        .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
    IO.println(unique);
    IO.println(joined);
    IO.println(byLength);
}

Output:

[api, java, stream]
java, stream, api, java
{3=1, 4=2, 6=1}

Notes

Ready-made collectors live in java.util.stream.Collectors — in a Java 25 compact source file this package is imported automatically. For a plain list toList() is shorter since Java 16. Collectors can be nested: the second argument of groupingBy() is a collector too.

See also

In the tutorial

  • Collectors — The collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.

Thanks for reading!

Donate to the site — we work hard for you.