Java Reference ยท Streams and Functional
The Collectors class
Overview of java.util.stream.Collectors: toList, toMap, groupingBy, partitioningBy, joining, counting, summing, mapping, teeing and writing a custom Collector.
A Collector describes how to gather the elements of a stream into a result: a list, a map, a string, a number. You pass one to Stream.collect(collector). The Collectors class is a toolbox of ready-made collectors, all static factory methods, so you rarely implement the Collector interface yourself.
Collectors fall into three groups: those that build containers (toList, toSet, toMap), those that summarize (counting, summingInt, averagingDouble, joining, minBy) and those that group or transform other collectors (groupingBy, partitioningBy, mapping, filtering, flatMapping, reducing, teeing). The second group is also used as the downstream of the third.
Map<Integer, List<String>> byLength = words.stream().collect(Collectors.groupingBy(String::length));
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 Stream.collect(Collector<? super T, A, R> collector)
| Factory | Result |
|---|---|
toList(), toSet(), toUnmodifiableList(), toCollection(supplier) |
A collection. See collectors-tolist. |
toMap(key, value[, merge[, supplier]]) |
A Map. |
groupingBy(classifier[, mapFactory][, downstream]) |
Map<K, ...>. See collectors-groupingby. |
partitioningBy(predicate[, downstream]) |
Map<Boolean, ...>. |
joining([delimiter[, prefix, suffix]]) |
A String. |
counting(), summingX, averagingX, minBy, maxBy, summarizingX |
Numeric summaries. |
mapping, filtering, flatMapping, reducing, collectingAndThen |
Adapters for downstream collectors. |
teeing(c1, c2, merger) |
Combines two collectors (Java 12). |
Usage notes
- Terminal:
collectconsumes the stream and runs the collector's supplier, accumulator, combiner and finisher; the combiner matters only for parallel streams. - Mutability is unspecified for
toList(),toSet(),toMap()andgroupingBy()results. Ask explicitly withtoCollection(...)or a map supplier when you need a specific type. Collectors.toList()vsStream.toList(): seeStream.toList().- Nulls:
toMap,toUnmodifiable*and several others reject null keys or values;groupingByrejects a null classifier result. - Downstream composition is the idiom for per-group statistics:
groupingBy(city, averagingInt(age)). - Custom collectors:
Collector.of(supplier, accumulator, combiner, finisher)builds one inline.