Java Reference ยท Streams and Functional
Collectors.toList(), toSet() and toMap()
Reference for Java Collectors.toList(), toSet(), toMap() and toCollection(): gather stream elements, handle duplicate keys and choose the collection type.
These are the collectors that turn a stream into an ordinary container. toList() gathers elements into a List, toSet() into a Set (dropping duplicates) and toMap() into a Map using functions that compute the key and the value of each element. toCollection(supplier) lets you choose the exact collection class, for example a TreeSet or LinkedList.
toMap() is the one with traps: two elements with the same key throw IllegalStateException unless you supply a merge function.
List<String> list = stream.collect(Collectors.toList()); Map<String, Integer> lengths = words.stream() .collect(Collectors.toMap(w -> w, 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
static <T> Collector<T, ?, List<T>> toList() static <T> Collector<T, ?, Set<T>> toSet() static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> factory) static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) static <T, K, U> Collector<T, ?, Map<K, U>> toMap(keyMapper, valueMapper, BinaryOperator<U> mergeFunction) static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(keyMapper, valueMapper, mergeFunction, Supplier<M> mapFactory)
| Name | Description |
|---|---|
keyMapper, valueMapper |
Compute the key and value from an element. |
mergeFunction |
Resolves two values for the same key. |
mapFactory / factory |
Creates the result container, such as TreeMap::new. |
Throws: IllegalStateException on a duplicate key without a merge function; NullPointerException if a value is null.
Usage notes
- Type not guaranteed: the plain collectors usually produce
ArrayList,HashSetandHashMap, but the contract does not say so; do not rely on iteration order of a set or map. - Ordered or sorted results: ask with
toCollection(LinkedHashSet::new)or aTreeMapfactory. - Null values:
toMapusesHashMap.merge, which rejectsnullvalues. Filter them out or use a loop. - Null keys are allowed by the default
HashMap, but not byTreeMap. - Unmodifiable variants:
toUnmodifiableList/Set/Mapreturn immutable collections and rejectnullelements. - Java 16:
Stream.toList()is shorter when you only need a read-only list. - Concurrent maps:
toConcurrentMapsuits parallel streams.