Java Collectors.toMap: Collecting Streams into Maps
Turn a Java stream into a map with Collectors.toMap: key and value functions, Function.identity(), the duplicate-key IllegalStateException, merge functions, choosing TreeMap or LinkedHashMap, the null-value trap, toUnmodifiableMap and toConcurrentMap.
kvi5hnuCode Sprout team member8 min readOn this page
A list is fine when you process results in order. Often, though, you want to look things up: a person by ID, a product by SKU, a word's length by the word. Collectors.toMap builds a map straight from a stream. It looks simple, but it has a few sharp edges: duplicate keys, null values and the kind of map you get back. This article covers all of them.
Keys and values
toMap takes two functions. The first produces each element's key, the second its value:
public record Person(int id, String name) {}
Map<Integer, String> idToName = people.collect(Collectors.toMap(Person::id, Person::name));
Quite often the value should be the element itself. For that, pass Function.identity(), a function that returns its argument unchanged (p -> p works too):
Map<Integer, Person> idToPerson = people.collect(Collectors.toMap(Person::id, Function.identity()));
Duplicate keys
What if two elements produce the same key? The two-argument toMap refuses to guess which value you want and throws an IllegalStateException. Since Java 9 the message names the key and both values, which helps a lot when debugging:
Duplicate key 1001 (attempted merging values Peter and Pete)
If duplicates are expected, supply a third argument, a merge function. It receives the existing value and the new value for the same key and returns the value to keep. It can keep the existing one, take the new one or combine them:
(existing, replacement) -> existing // keep the first
(existing, replacement) -> replacement // keep the last
Integer::sum // add them up
Here is a map from each language's English name to its name in that language. Several locales share a language (German is spoken in Germany and in Switzerland), and we don't care which one wins:
Map<String, String> languageNames = locales.collect(Collectors.toMap(
l -> l.getDisplayLanguage(Locale.ENGLISH),
l -> l.getDisplayLanguage(l),
(existing, _) -> existing));
The _ is an unnamed variable (final in Java 22): a parameter the lambda doesn't use. Locales are covered properly in Part 7. Here they are just a convenient source of data.
A merge function can also build up collections. To find all languages spoken in each country, start every value as a one-element set and merge sets by taking their union:
Map<String, Set<String>> countryLanguages = locales.collect(Collectors.toMap(
l -> l.getDisplayCountry(Locale.ENGLISH),
l -> Set.of(l.getDisplayLanguage(Locale.ENGLISH)),
(a, b) -> {
var union = new HashSet<String>(a);
union.addAll(b);
return union;
}));
That works, but it's clumsy. Grouping elements by a property is so common that groupingBy, the subject of the next article, does it directly. Rule of thumb: use toMap when each key gets one value, and use groupingBy when each key gets a collection of elements.
Choosing the kind of map
The basic toMap returns some Map, a HashMap in practice, with no ordering guarantee. To choose the implementation, pass a map supplier as the fourth argument. Java offers no three-argument overload that takes keys, values and a supplier, so you must give a merge function too. If duplicates should still be an error, write one that throws:
Map<Integer, Person> idToPerson = people.collect(Collectors.toMap(
Person::id,
Function.identity(),
(_, _) -> { throw new IllegalStateException("duplicate id"); },
TreeMap::new));
TreeMap::newgives keys in sorted order.LinkedHashMap::newkeeps the stream's encounter order, which is handy when the stream is already sorted.() -> new EnumMap<>(Day.class)is compact and fast for enum keys.
The null-value trap
toMap builds the map with Map.merge, and merge doesn't accept null values. So if the value function ever returns null, the collector throws a NullPointerException, even though HashMap itself happily stores null values. null keys are accepted by toMap into a HashMap but not by toUnmodifiableMap. If values may be missing, filter those elements out first, map them to a placeholder such as an empty string or a dedicated constant (not Optional, which doesn't belong in collections), or collect with a plain loop that calls put.
Unmodifiable and concurrent maps
toUnmodifiableMap (Java 10) has the same two- and three-argument forms and returns a map that rejects changes. It also rejects null keys and values.
For each toMap method there's a matching toConcurrentMap, which returns a ConcurrentMap (a ConcurrentHashMap by default). With a parallel stream, ordinary toMap builds one map per thread and then merges them, which is costly for maps. toConcurrentMap has all threads insert into one shared concurrent map instead, which is usually faster. The trade-off: entries are no longer combined in stream order, so with a merge function such as "keep the first", which value wins is no longer predictable. Use it when the merge function doesn't care about order, such as Integer::sum.
A complete example
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Solution {
record Person(int id, String name) {}
static Stream<Person> people() {
return Stream.of(new Person(1001, "Peter"), new Person(1002, "Paul"), new Person(1003, "Mary"));
}
static Stream<Locale> locales() {
return Stream.of(Locale.of("de", "DE"), Locale.of("de", "CH"), Locale.of("fr", "CH"),
Locale.of("it", "CH"), Locale.of("fr", "FR"), Locale.of("en", "US"), Locale.of("es", "US"));
}
public static void main(String[] args) {
// key and value functions
Map<Integer, String> idToName = people().collect(Collectors.toMap(Person::id, Person::name));
System.out.println("idToName: " + new TreeMap<>(idToName));
// the element itself as the value
Map<Integer, Person> idToPerson = people().collect(Collectors.toMap(Person::id, Function.identity()));
System.out.println("idToPerson.get(1002): " + idToPerson.get(1002));
// duplicate keys throw by default
try {
Stream.of(new Person(1001, "Peter"), new Person(1001, "Pete"))
.collect(Collectors.toMap(Person::id, Person::name));
} catch (IllegalStateException e) {
System.out.println("IllegalStateException: " + e.getMessage());
}
// a merge function resolves conflicts: keep the first value
Map<String, String> languageNames = locales().collect(Collectors.toMap(
l -> l.getDisplayLanguage(Locale.ENGLISH),
l -> l.getDisplayLanguage(l),
(existing, _) -> existing,
TreeMap::new));
System.out.println("languageNames: " + languageNames);
// merging sets: all languages per country
Map<String, Set<String>> countryLanguages = locales().collect(Collectors.toMap(
l -> l.getDisplayCountry(Locale.ENGLISH),
l -> Set.of(l.getDisplayLanguage(Locale.ENGLISH)),
(a, b) -> {
var union = new TreeSet<String>(a);
union.addAll(b);
return union;
},
TreeMap::new));
System.out.println("countryLanguages: " + countryLanguages);
// counting with a merge function
Map<Character, Integer> initials = Stream.of("apple", "avocado", "banana", "blueberry", "cherry", "apricot")
.collect(Collectors.toMap(s -> s.charAt(0), _ -> 1, Integer::sum, TreeMap::new));
System.out.println("words per initial: " + initials);
// insertion order with LinkedHashMap
Map<String, Integer> lengths = Stream.of("pear", "fig", "banana")
.collect(Collectors.toMap(Function.identity(), String::length, (a, _) -> a, LinkedHashMap::new));
System.out.println("LinkedHashMap keeps stream order: " + lengths);
// null values are rejected
try {
Stream.of("x").collect(Collectors.toMap(Function.identity(), _ -> (String) null));
} catch (NullPointerException e) {
System.out.println("null value: NullPointerException");
}
// unmodifiable maps
Map<Integer, String> frozen = people().collect(Collectors.toUnmodifiableMap(Person::id, Person::name));
try {
frozen.put(1004, "Ann");
} catch (UnsupportedOperationException e) {
System.out.println("toUnmodifiableMap: put throws UnsupportedOperationException");
}
// concurrent maps for parallel streams
var concurrent = IntStream.rangeClosed(1, 1000).boxed().parallel()
.collect(Collectors.toConcurrentMap(n -> n % 3, _ -> 1, Integer::sum));
System.out.println(concurrent.getClass().getSimpleName() + " counts by n % 3: " + new TreeMap<>(concurrent));
}
}
idToName: {1001=Peter, 1002=Paul, 1003=Mary}
idToPerson.get(1002): Person[id=1002, name=Paul]
IllegalStateException: Duplicate key 1001 (attempted merging values Peter and Pete)
languageNames: {English=English, French=français, German=Deutsch, Italian=italiano, Spanish=español}
countryLanguages: {France=[French], Germany=[German], Switzerland=[French, German, Italian], United States=[English, Spanish]}
words per initial: {a=3, b=2, c=1}
LinkedHashMap keeps stream order: {pear=4, fig=3, banana=6}
null value: NullPointerException
toUnmodifiableMap: put throws UnsupportedOperationException
ConcurrentHashMap counts by n % 3: {0=333, 1=334, 2=333}
The locales are created explicitly and the names are requested in English, so the output doesn't depend on your computer's settings. TreeMap wrappers make the printed order predictable.
Common questions
How do I count how often each word occurs?
words.stream().collect(Collectors.toMap(w -> w, w -> 1, Integer::sum)) gives a Map<String, Integer>. The equivalent groupingBy(w -> w, counting()) from the next articles gives Long counts and is the more common idiom.
How do I sort a map by its values?
A map has no "sort by value" operation, so stream its entries, sort them and collect into a LinkedHashMap, which keeps that order: map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new)). If you only need the top entries, sorted(...).limit(10).toList() on the entries is simpler.
How do I invert a map, swapping keys and values?
map.entrySet().stream().collect(toMap(Map.Entry::getValue, Map.Entry::getKey)). If several keys share a value, you get the duplicate-key exception. Use a merge function to choose one, or groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toList())) to keep all of them.
Does toMap keep the order of my stream?
Not with the default HashMap. Pass LinkedHashMap::new as the fourth argument (with a merge function) to keep the encounter order, or TreeMap::new for sorted keys.
Can a key be null?
With plain toMap into a HashMap, yes: a null key is stored like any other. toUnmodifiableMap and toConcurrentMap reject it, as does a TreeMap with natural ordering. null values are rejected by all forms.
Is toMap better than a loop with put?
It is shorter and catches duplicate keys for you, where put would silently overwrite. A loop is still fine, and it is the easiest way to allow null values.
API reference
java.util.stream.Collectors
| Method | Description |
|---|---|
toMap(Function keyMapper, Function valueMapper) | a map with the mapped keys and values; IllegalStateException on duplicate keys |
toMap(keyMapper, valueMapper, BinaryOperator<U> mergeFunction) | mergeFunction(existing, new) decides the value for duplicate keys |
toMap(keyMapper, valueMapper, mergeFunction, Supplier<M> mapFactory) | collects into the map that mapFactory creates, such as TreeMap::new |
toUnmodifiableMap(keyMapper, valueMapper), toUnmodifiableMap(keyMapper, valueMapper, mergeFunction) (Java 10) | an unmodifiable map; no null keys or values |
toConcurrentMap(keyMapper, valueMapper), toConcurrentMap(..., mergeFunction), toConcurrentMap(..., mergeFunction, mapFactory) | a ConcurrentMap filled concurrently, without encounter order |
java.util.function.Function<T, R>
| Method | Description |
|---|---|
static <T> Function<T, T> identity() | a function that returns its argument |
Summary
Collectors.toMap(keyFn, valueFn)builds a map. UseFunction.identity()when the element is the value.- Duplicate keys throw
IllegalStateException, unless you supply a merge function that picks or combines values. - A fourth argument chooses the map type, such as
TreeMap::neworLinkedHashMap::new. That form also requires a merge function. - A
nullvalue makestoMapthrowNullPointerException. toUnmodifiableMapgives a read-only map.toConcurrentMapfills one shared map, which suits parallel streams with order-independent merges.- When each key should get a collection of elements, use
groupingByinstead.
Practice Questions
What happens when you run Stream.of("a", "bb", "cc").collect(Collectors.toMap(String::length, s -> s))?
It throws an IllegalStateException, because "bb" and "cc" both have length 2. The message is Duplicate key 2 (attempted merging values bb and cc). Add a merge function to resolve it.
Write a collector that maps each word to the number of times it occurs, using toMap.
Collectors.toMap(w -> w, w -> 1, Integer::sum). Each word starts with a count of 1, and duplicates are added together. Article 11 shows the groupingBy plus counting() alternative.
You want a map sorted by key but don't expect duplicate keys. Why must you still write a merge function?
The only toMap overload that accepts a map supplier is the four-argument one, which also takes a merge function. Pass one that throws, such as (_, _) -> { throw new IllegalStateException(); }, to keep the "duplicates are an error" behavior.
A colleague's toMap throws NullPointerException, but none of the stream elements are null. What's the likely cause?
The value function returns null for some element. toMap inserts with Map.merge, which rejects null values even for a HashMap. Filter those elements out, use a placeholder value, or build the map with a loop.
Why can toConcurrentMap give a different result from toMap with the merge function (a, b) -> a on a parallel stream?
toMap combines per-thread maps in encounter order, so "keep the first" really keeps the first element in the stream. toConcurrentMap inserts into one shared map from many threads in no particular order, so whichever thread arrives first wins, and that can change from run to run.
Previous: Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
Next: Java groupingBy and partitioningBy: Grouping Stream Elements
Related reading
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
- Java Optional: Getting, Consuming and Transforming Optional Values

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.