Collectors.toMap() in Java
Collectors.toMap() is a static method of java.util.stream.Collectors, available since Java 8, that returns a Collector which builds a Map from stream elements. You provide one function that computes each element's key and one that computes its value; optional extra arguments decide what to do with duplicate keys and which Map type to create.
It is the standard way to index a list by id or to build a lookup table. This tutorial covers all three overloads, duplicate keys, null values, ordering, and the unmodifiable and concurrent variants.
1. Syntax and Method Signatures
// java.util.stream.Collectors (Java 8)
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)
static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapFactory)
// Java 10: read-only map; also toConcurrentMap(...) for parallel streams
static <T, K, U> Collector<T, ?, Map<K, U>> toUnmodifiableMap(...)
keyMapper and valueMapper are Functions. The mergeFunction is a BinaryOperator<U> that receives the existing and the new value for a repeated key and returns the value to keep. mapFactory is a Supplier such as TreeMap::new.
2. How toMap() Works
For every element, toMap() computes the key and the value and inserts them. If the key is already present, the two-argument version throws IllegalStateException with a message such as Duplicate key Asha (attempted merging values 500 and 200). The three- and four-argument versions call the merge function instead.
Values are inserted with Map.merge(), which does not accept null, so a null value throws NullPointerException. The default map is a HashMap with no defined order; supply LinkedHashMap::new or TreeMap::new for insertion or sorted order.
IllegalStateException. With Integer::sum, values for the same key are added.3. Java Examples
Example 1: Indexing a list by id (Java 16+)
Build a lookup table from product SKU to product, so prices can be found without scanning the list.
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ProductIndex {
record Product(String sku, String name, int price) { }
public static void main(String[] args) {
List<Product> products = List.of(
new Product("P-100", "Kettle", 1499),
new Product("P-200", "Toaster", 1999),
new Product("P-300", "Mixer", 3299));
Map<String, Product> bySku = products.stream()
.collect(Collectors.toMap(Product::sku, Function.identity()));
System.out.println("P-200 costs " + bySku.get("P-200").price());
System.out.println("Known SKU P-999? " + bySku.containsKey("P-999"));
}
}
P-200 costs 1999 Known SKU P-999? false
How it works: Function.identity() uses the element itself as the value. Each lookup is now a fast get() instead of a scan.
Example 2: Merging duplicate keys (Java 16+)
Total the order amounts per customer, where a customer can have several orders.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class TotalPerCustomer {
record Order(String id, String customer, int amount) { }
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("O1", "Asha", 500), new Order("O2", "Ravi", 300), new Order("O3", "Asha", 200));
Map<String, Integer> totals = orders.stream()
.collect(Collectors.toMap(Order::customer, Order::amount, Integer::sum, TreeMap::new));
System.out.println(totals);
try {
orders.stream().collect(Collectors.toMap(Order::customer, Order::amount));
} catch (IllegalStateException e) {
System.out.println("Without merge: " + e.getMessage());
}
}
}
{Asha=700, Ravi=300}
Without merge: Duplicate key Asha (attempted merging values 500 and 200)
How it works: Integer::sum adds the amounts for repeated customers, and TreeMap::new sorts the keys. The second call shows the exception you get when no merge function is given.
Example 3: Keeping the first or the latest value (Java 16+)
Several login events exist per user. Build one map with each user's first login and one with the latest.
import java.time.LocalTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class FirstAndLatestLogin {
record Login(String user, LocalTime at) { }
public static void main(String[] args) {
List<Login> logins = List.of(
new Login("neha", LocalTime.of(9, 5)), new Login("arjun", LocalTime.of(9, 20)),
new Login("neha", LocalTime.of(13, 40)), new Login("arjun", LocalTime.of(11, 0)));
Map<String, LocalTime> first = logins.stream()
.collect(Collectors.toMap(Login::user, Login::at, (a, b) -> a, LinkedHashMap::new));
Map<String, LocalTime> latest = logins.stream()
.collect(Collectors.toMap(Login::user, Login::at,
(a, b) -> a.isAfter(b) ? a : b, LinkedHashMap::new));
System.out.println("First: " + first);
System.out.println("Latest: " + latest);
}
}
First: {neha=09:05, arjun=09:20}
Latest: {neha=13:40, arjun=11:00}
How it works: The merge function decides the policy: (a, b) -> a keeps the existing value, and a comparison keeps the later time. LinkedHashMap::new keeps users in first-seen order.
Example 4: Null values and how to handle them (Java 16+)
Map employees to their optional manager, where some have none.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class ToMapNullValues {
record Employee(String name, String manager) { }
public static void main(String[] args) {
List<Employee> staff = List.of(new Employee("Ira", "Dev"), new Employee("Dev", null), new Employee("Sam", "Dev"));
try {
staff.stream().collect(Collectors.toMap(Employee::name, Employee::manager));
} catch (NullPointerException e) {
System.out.println("toMap with a null value: NullPointerException");
}
Map<String, String> managers = staff.stream()
.collect(TreeMap::new, (map, e) -> map.put(e.name(), e.manager()), Map::putAll);
System.out.println(managers);
Map<String, String> withDefault = staff.stream()
.collect(Collectors.toMap(Employee::name, e -> e.manager() == null ? "(none)" : e.manager()));
System.out.println(new TreeMap<>(withDefault));
}
}
toMap with a null value: NullPointerException
{Dev=null, Ira=Dev, Sam=Dev}
{Dev=(none), Ira=Dev, Sam=Dev}
How it works: toMap() rejects null values. Either replace them with a default, or use the three-argument collect() with put(), which allows nulls in a HashMap or TreeMap but also silently overwrites duplicate keys.
4. Real-World Use Cases
- Lookup tables: index customers, products or accounts by id for fast access.
- Configuration: turn a list of settings into a key-value map.
- Aggregation: sum, count or pick the latest value per key with a merge function.
- Joining data sets: build a map from one list and enrich another list with it.
5. Important Points
- Duplicate keys throw
IllegalStateExceptionunless you pass a merge function. - Null values throw
NullPointerException; null keys are allowed in aHashMapbut rejected byTreeMap. - Order: the default
HashMaphas none; useLinkedHashMap::neworTreeMap::new. - Mutability: the default map type and mutability are not specified; use the four-argument form for a guaranteed type, or
toUnmodifiableMap()(Java 10). - Parallel: merging maps is costly;
toConcurrentMap()can be faster when order does not matter.
6. toMap() vs groupingBy()
| Collector | Duplicate keys | Values per key | Best for |
|---|---|---|---|
toMap(k, v) | Exception | One | Keys known to be unique |
toMap(k, v, merge) | Merged | One (merged) | Sums, latest value, first value |
toMap(k, v, merge, TreeMap::new) | Merged | One | Sorted or ordered maps |
groupingBy(k) | Grouped | A list of all elements | Keeping every element per key |
toUnmodifiableMap(k, v) | Exception | One | Read-only results (Java 10) |
If you need all elements per key, not one merged value, use groupingBy().
7. Common Mistakes and Best Practices
Assuming keys are unique
Data that is unique today, such as email addresses, may not be tomorrow. A missing merge function turns that into a runtime failure. Decide on a merge policy explicitly, as in Examples 2 and 3.
Using toMap() when you need groups
Map<String, Order> byCustomer = orders.stream()
.collect(Collectors.toMap(Order::customer, o -> o, (a, b) -> a)); // silently drops other orders
Map<String, List<Order>> byCustomer = orders.stream()
.collect(Collectors.groupingBy(Order::customer)); // keeps every order
Other mistakes to avoid
- Expecting insertion order from the default map.
- Mapping to a nullable value without a default.
- Writing
e -> ewhereFunction.identity()is clearer (both work).
8. Summary
toMap()builds a map from key and value functions.- Duplicate keys throw unless you give a merge function; null values always throw.
- Use the four-argument form for a specific map type such as
LinkedHashMaporTreeMap. - Use
groupingBy()when you need every element per key.
9. References
Frequently Asked Questions (FAQ)
Q1. What does Collectors.toMap() do?
It returns a collector that builds a Map from stream elements, using one function to compute each key and another to compute each value.
Q2. Why does toMap() throw IllegalStateException: Duplicate key?
Two elements produced the same key and no merge function was given. Pass a third argument, a BinaryOperator that decides which value to keep or how to combine them, such as (a, b) -> a or Integer::sum.
Q3. Why does toMap() throw NullPointerException?
toMap() inserts values with Map.merge(), which does not accept null values. Replace null values with a default, or collect with a supplier and put().
Q4. How do I keep the insertion order in toMap()?
Use the four-argument version with LinkedHashMap::new as the map factory: toMap(key, value, (a, b) -> a, LinkedHashMap::new).
Q5. What is the difference between toMap() and groupingBy()?
toMap() stores one value per key and needs a merge function for duplicates. groupingBy() stores a collection of all elements, or a downstream result, for each key.