Java Reference ยท Streams and Functional
Java Stream.collect() method
Reference for Java Stream.collect(): gather elements into lists, sets, maps and strings with Collectors, or write your own supplier, accumulator and combiner.
collect() is a terminal operation that performs a mutable reduction: it accumulates the elements into a mutable result container such as a List, a Map or a StringBuilder. Most of the time you pass a ready-made Collector from the Collectors class; there is also a three-argument form for building your own.
Because the container is created per thread and the partial results are merged at the end, collect() is safe to use on parallel streams as long as the supplied functions are stateless and the container is not shared.
Set<String> unique = words.stream().collect(Collectors.toSet());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
<R, A> R collect(Collector<? super T, A, R> collector) <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)
| Name | Description |
|---|---|
collector |
Describes the reduction: supplier, accumulator, combiner, optional finisher and characteristics. |
supplier |
Creates a new empty result container. |
accumulator |
Folds one element into the container. |
combiner |
Merges two containers (used for parallel streams). |
Returns: the reduced result.
Usage notes
- Which list?
Collectors.toList()makes no promise about the list type or mutability (today anArrayList).Stream.toList()(Java 16) returns an unmodifiable list and allows nulls;Collectors.toUnmodifiableList()rejects nulls. toMappitfalls: duplicate keys throwIllegalStateExceptionunless you pass a merge function, and null values throwNullPointerException. Pass a map supplier (TreeMap::new) when order matters.toSet/groupingByuse hash maps, so iteration order is arbitrary; wrap in aTreeMap/TreeSetor pass a supplier when printing.- Do not mutate shared state in the accumulator; the whole point is that each thread gets its own container.
- Down-stream collectors (
groupingBy(key, counting()),mapping,filtering,flatMapping,summingInt,teeing) compose reductions without extra passes. - Reduction vs collection: use
reduce()for immutable values (numbers, strings) andcollect()for mutable containers; usingreduceto build a list copies it repeatedly. - Custom collectors with
Collector.of(...)are rarely needed; try a combination of standard ones first.