Skip to lesson

toMap and duplicate keys

Collectors.toMap turns a stream into a Map: one function picks the key for each element and a second function picks the value. It is how a list of students becomes a lookup table from roll number to student.

From a list to a lookup map

A list is slow to search: to find roll number 104 you walk the list from the start. A HashMap from roll number to student finds it in one step. The old way is a loop: create the map, then put(s.roll(), s) for each student.

Example 1 · Roll number to name, the loop way and the toMap way

RollMapDemo.javaJava
import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.function.Function;import java.util.stream.Collectors;
record Student(int roll, String name, String branch) {}
public class RollMapDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student(101, "Asha", "CSE"),                new Student(102, "Ravi", "ECE"),                new Student(103, "Neha", "CSE"),                new Student(104, "Imran", "MECH"));
        // old way        Map<Integer, String> loopMap = new HashMap<>();        for (Student s : students) {            loopMap.put(s.roll(), s.name());        }
        // new way        Map<Integer, String> names = students.stream()                .collect(Collectors.toMap(Student::roll, Student::name));        System.out.println("Same map: " + names.equals(loopMap));        System.out.println("Roll 103 is " + names.get(103));        System.out.println("Roll 110 is " + names.get(110));
        Map<Integer, Student> byRoll = students.stream()                .collect(Collectors.toMap(Student::roll, Function.identity()));        Student s = byRoll.get(104);        System.out.println("Roll 104: " + s.name() + ", " + s.branch());    }}
Output
Same map: true
Roll 103 is Neha
Roll 110 is null
Roll 104: Imran, MECH

What this code does

  • toMap(Student::roll, Student::name) calls roll() for the key and name() for the value of every student. It builds the same map as the loop with put. A missing key such as 110 gives null, as with any map.
  • Function.identity() returns each element unchanged, so the value is the whole Student record. That is the usual way to build a lookup table by id.
  • Why toMap: the loop silently replaces a repeated key with put. toMap throws on a duplicate unless you give a merge function, so the clash cannot go unnoticed.

Collectors.toMap(keyFunction, valueFunction) does the same. For each element it calls the key function, calls the value function, and puts the pair in a new map. toMap(Student::roll, Student::name) builds roll number → name. When the value should be the element itself, use Function.identity(), a function that returns its input unchanged. toMap(Student::roll, Function.identity()) builds roll number → the whole Student.

Like toSet(), plain toMap gives a HashMap today, with no fixed order. Read single values with get, or ask for a sorted map with a supplier (covered below).

Duplicate keys throw IllegalStateException

A map holds one value per key. What if two students share roll number 101 because of a typing mistake? The loop with put would silently replace the first student with the second, and nobody would notice the lost record.

toMap with roll numbers as keys. Entry 101 Asha goes into the map, then 102 Ravi, then a second 101 Neha collides with key 101 and throws IllegalStateException: Duplicate key 101. Adding the merge function (a, b) -> b keeps the newer value and gives {101=Neha, 102=Ravi}.

Example 2 · Two students with one roll number

DuplicateRollDemo.javaJava
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
record Student(int roll, String name) {}
public class DuplicateRollDemo {    public static void main(String[] args) {        // a typing mistake: Kiran was given Asha's roll number        List<Student> students = List.of(                new Student(101, "Asha"),                new Student(102, "Ravi"),                new Student(101, "Kiran"));
        try {            Map<Integer, String> names = students.stream()                    .collect(Collectors.toMap(Student::roll, Student::name));            System.out.println(names);        } catch (IllegalStateException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
Error: Duplicate key 101 (attempted merging values Asha and Kiran)

What this code does

  • Roll number 101 appears twice. Two-argument toMap does not choose a winner: it throws IllegalStateException, and the message names the key and both values.
  • This is a feature. A silent overwrite would lose Asha's record without any warning, and the report built from the map would be wrong.

toMap with two arguments refuses to guess. On the second 101 it throws IllegalStateException with a message such as Duplicate key 101 (attempted merging values Asha and Kiran). Failing loudly is the safer choice: it tells you the data has a problem. So before using two-argument toMap, ask: can two elements ever give the same key? Roll numbers in one class should not. Cities of customers, payee names in a UPI history or product categories certainly can.

Fix the error

Fix the toMap crash

Read the real error, then pick the line that fixes it.

Round 1 of 2

Two students share roll number 101. Keep the later one.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
record Student(int roll, String name) {}
public class RollMap {
public static void main(String[] args) {
List<Student> list = List.of(new Student(101, "Asha"), new Student(101, "Neha"));
Map<Integer, String> byRoll = list.stream()
.collect(Collectors.toMap(Student::roll, Student::name));
System.out.println(byRoll);
}
}

Error

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 101 (attempted merging values Asha and Neha)
	at RollMap.main(RollMap.java:11)

A merge function decides what to keep

The third argument of toMap is a merge function: when a key already has a value, Java calls it with the old value and the new value, and stores whatever it returns.

Example 3 · Merge functions: keep first, keep last, add up

UpiTotalsDemo.javaJava
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
record Payment(String payee, int amount) {}
public class UpiTotalsDemo {    public static void main(String[] args) {        List<Payment> history = List.of(                new Payment("Bookstore", 60),                new Payment("Metro", 40),                new Payment("Bookstore", 85),                new Payment("Xerox", 20),                new Payment("Bookstore", 30),                new Payment("Metro", 40));
        Map<String, Integer> total = history.stream()                .collect(Collectors.toMap(Payment::payee, Payment::amount, Integer::sum));        Map<String, Integer> first = history.stream()                .collect(Collectors.toMap(Payment::payee, Payment::amount, (oldV, newV) -> oldV));        Map<String, Integer> last = history.stream()                .collect(Collectors.toMap(Payment::payee, Payment::amount, (oldV, newV) -> newV));
        for (String payee : List.of("Bookstore", "Metro", "Xerox")) {            System.out.println(payee + ": total " + total.get(payee)                    + ", first " + first.get(payee) + ", last " + last.get(payee));        }    }}
Output
Bookstore: total 175, first 60, last 30
Metro: total 80, first 40, last 40
Xerox: total 20, first 20, last 20

What this code does

  • Bookstore appears three times. With Integer::sum, Java merges 60 and 85 into 145, then 145 and 30 into 175. Keep-first stores 60 and ignores later values; keep-last ends with 30.
  • Xerox appears once, so the merge function never runs for it and all three maps hold 20. The loop prints in a fixed order because it walks a list, not the HashMap.
  • Keep the first value: (oldV, newV) -> oldV.
  • Keep the last value: (oldV, newV) -> newV, for example the latest phone number of a contact.
  • Add them up: Integer::sum, for example the total amount paid to each UPI payee.
  • Join them: (a, b) -> a + ", " + b, for example all subjects a teacher handles.
A merge function runs only for repeated keys. For a key seen once, the value is stored as it is.

Choosing the map type with a supplier

The four-argument form is toMap(keyFn, valueFn, mergeFn, mapSupplier). The supplier creates the empty map, so TreeMap::new gives keys in sorted order and LinkedHashMap::new keeps the order in which keys first appeared.

Example 4 · Sorted or first-seen keys with a map supplier

PriceMapDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Item(String name, int price) {}
public class PriceMapDemo {    public static void main(String[] args) {        List<Item> priceList = List.of(                new Item("Eraser", 15),                new Item("Notebook", 60),                new Item("Pen", 10),                new Item("Backpack", 140));
        TreeMap<String, Integer> sorted = priceList.stream()                .collect(Collectors.toMap(Item::name, Item::price,                        (a, b) -> a, TreeMap::new));        System.out.println("A to Z: " + sorted);        System.out.println("First item: " + sorted.firstKey());
        LinkedHashMap<String, Integer> asListed = priceList.stream()                .collect(Collectors.toMap(Item::name, Item::price,                        (a, b) -> a, LinkedHashMap::new));        System.out.println("As listed: " + asListed);
        Map<String, Integer> strict = priceList.stream()                .collect(Collectors.toMap(Item::name, Item::price,                        (a, b) -> { throw new IllegalStateException("Same item twice"); },                        TreeMap::new));        System.out.println("Strict map size: " + strict.size());    }}
Output
A to Z: {Backpack=140, Eraser=15, Notebook=60, Pen=10}
First item: Backpack
As listed: {Eraser=15, Notebook=60, Pen=10, Backpack=140}
Strict map size: 4

What this code does

  • The fourth argument creates the map. TreeMap::new sorts the keys, so the map prints A to Z and firstKey() works. LinkedHashMap::new keeps the order of the price list.
  • A supplier always needs a merge function before it. When duplicates would be a bug, a merge function that throws keeps the strict behaviour of two-argument toMap.

There is no three-argument form with a supplier, so you must write a merge function even when you expect no duplicates. If duplicates would be a bug, make the merge function throw: (a, b) -> { throw new IllegalStateException("Duplicate roll number"); }.

Trap: a null value throws NullPointerException

A HashMap itself can store null values, so many students expect toMap to allow them. It does not. If the value function returns null for any element, toMap throws NullPointerException.

Example 5 · Trap: an empty email gives NullPointerException

NullValueDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(int roll, String email) {}
public class NullValueDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student(101, "asha@college.in"),                new Student(102, null),                new Student(103, "neha@college.in"));
        try {            students.stream().collect(Collectors.toMap(Student::roll, Student::email));        } catch (NullPointerException e) {            System.out.println("toMap failed: a value was null");        }
        Map<Integer, String> emails = students.stream()                .collect(Collectors.toMap(Student::roll,                        s -> s.email() == null ? "not given" : s.email(),                        (a, b) -> a, TreeMap::new));        System.out.println(emails);    }}
Output
toMap failed: a value was null
{101=asha@college.in, 102=not given, 103=neha@college.in}

What this code does

  • Student 102 has no email, so the value function returns null and toMap throws NullPointerException. A plain HashMap.put would accept it, which surprises many people.
  • The fix gives a default value inside the value function. Another fix is to filter out students with no email before collecting, when they should not be in the map at all.

This bites with real data: a student who left the email field empty, a product with no discount set. Fix it at the source: give a default such as "not given" in the value function, or filter those elements out first. If you truly need null values, use a loop with put instead of toMap.

Next step

Check your understanding

11 quick questions