00:00

Collectors.toMap() in Java

Last updated:

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

Collectors.java (API)
// 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.

toMap() with a duplicate key and a merge function Three orders: O1 for customer Asha worth 500, O2 for Ravi worth 300, O3 for Asha worth 200. toMap with key customer and value amount puts Asha 500 and Ravi 300. When O3 arrives with the existing key Asha, the merge function Integer::sum combines 500 and 200 into 700. ELEMENT KEY, VALUE MAP AFTER O1 Asha, 500 Asha -> 500 {Asha=500} O2 Ravi, 300 Ravi -> 300 {Asha=500, Ravi=300} O3 Asha, 200 duplicate: merge {Asha=700, Ravi=300}
Figure 1: Without a merge function the third order would throw 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.

ProductIndex.java
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"));
    }
}
Output
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.

TotalPerCustomer.java
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());
        }
    }
}
Output
{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.

FirstAndLatestLogin.java
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);
    }
}
Output
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.

ToMapNullValues.java
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));
    }
}
Output
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 IllegalStateException unless you pass a merge function.
  • Null values throw NullPointerException; null keys are allowed in a HashMap but rejected by TreeMap.
  • Order: the default HashMap has none; use LinkedHashMap::new or TreeMap::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()

CollectorDuplicate keysValues per keyBest for
toMap(k, v)ExceptionOneKeys known to be unique
toMap(k, v, merge)MergedOne (merged)Sums, latest value, first value
toMap(k, v, merge, TreeMap::new)MergedOneSorted or ordered maps
groupingBy(k)GroupedA list of all elementsKeeping every element per key
toUnmodifiableMap(k, v)ExceptionOneRead-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

Lossy
Map<String, Order> byCustomer = orders.stream()
        .collect(Collectors.toMap(Order::customer, o -> o, (a, b) -> a));   // silently drops other orders
Better
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 -> e where Function.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 LinkedHashMap or TreeMap.
  • Use groupingBy() when you need every element per key.

9. References