Collectors.toMap()
A collector that builds a map from stream elements.
Available since: Java 8
Syntax
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(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction)Parameters
| Parameter | Type | Description |
|---|---|---|
| keyMapper | Function<? super T, ? extends K> | Extracts the key from an element. |
| valueMapper | Function<? super T, ? extends U> | Extracts the value from an element. |
| mergeFunction | BinaryOperator<U> | Optional: what to do on a duplicate key. |
Return value
Collector<T, ?, Map<K, U>>A collector into a map.
Examples
A name to length map:
void main() {
Map<String, Integer> lengths = Stream.of("Anna", "Oleg", "Ivanka")
.collect(Collectors.toMap(n -> n, String::length));
IO.println(lengths.get("Ivanka"));
}Output:
6A duplicate key without a merge function is an error:
void main() {
List<String> words = List.of("apple", "avocado", "banana");
try {
words.stream().collect(Collectors.toMap(w -> w.charAt(0), w -> w));
} catch (IllegalStateException e) {
IO.println(e.getMessage());
}
Map<Character, String> joined = words.stream()
.collect(Collectors.toMap(w -> w.charAt(0), w -> w, (a, b) -> a + "+" + b, TreeMap::new));
IO.println(joined);
}Output:
Duplicate key a (attempted merging values apple and avocado)
{a=apple+avocado, b=banana}Notes
If two elements produce the same key, the call without a third argument throws IllegalStateException: Duplicate key. The third argument resolves the conflict and the fourth sets the map type (TreeMap::new, LinkedHashMap::new). A null value is not allowed — NullPointerException. To group several elements under one key use groupingBy().
See also
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
- HashMap — A map backed by a hash table: fast lookup by key, no guaranteed order.
- Map.merge() — Adds a value under a key or combines it with the existing one.
Related recipes
In the tutorial
- Collectors — The collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.