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
| Parameter | Type | Description |
|---|---|---|
| collector | Collector<? 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
- Stream.toList() — Gathers stream elements into an unmodifiable list.
- Collectors.toMap() — A collector that builds a map from stream elements.
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
- Collectors.joining() — A collector that joins the strings of a stream into one.
In the tutorial
- Collectors — The collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.