Collectors ToMap Null Value Trap

Collectors.toMap throws NullPointerException when the value mapper returns null; collect into a HashMap by hand or map a default to keep nullable fields.

JavaData Integrity

Code

snippet
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LabelIndex {

    record Item(String sku, String label) {}

    public static void main(String[] args) {
        List<Item> items = List.of(
                new Item("A-1", "widget"),
                new Item("B-2", null));

        // toMap 的值映射返回 null 时:HashMap.merge 收到 null 直接 NPE,
        // 整条流水线在运行时崩溃,而不是安静地存一个 null 值
        try {
            items.stream().collect(Collectors.toMap(Item::sku, Item::label));
        } catch (NullPointerException e) {
            System.out.println("toMap rejected null value");
        }

        // 修正一:三参 collect 手工塞入,null 值放行
        Map<String, String> tolerant = items.stream()
                .collect(HashMap::new,
                        (m, item) -> m.put(item.sku(), item.label()),
                        HashMap::putAll);
        System.out.println(tolerant);

        // 修正二:先把 null 映射成显式默认值
        Map<String, String> defaulted = items.stream()
                .collect(Collectors.toMap(Item::sku,
                        item -> item.label() == null ? "(none)" : item.label()));
        System.out.println(defaulted);
    }
}

How it works

Count the classes LabelIndex and Item and the function main as the entire surface area of Collectors ToMap Null Value Trap.

Stream stages compose left to right — nothing executes until the terminal operation runs.

Putting it to use

Running the file prints labeled results such as toMap rejected null value — each operation’s effect is visible in the output.

Core lines

items.stream().collect(Collectors.toMap(Item::sku, Item::label));
.collect(Collectors.toMap(Item::sku,
item -> item.label() == null ? "(none)" : item.label()));
Map<String, String> tolerant = items.stream()
.collect(HashMap::new,
(m, item) -> m.put(item.sku(), item.label()),
HashMap::putAll);

Interactive Tools for This Topic

FAQ

What does Collectors ToMap Null Value Trap print when run?
Running the file directly is enough — expect labeled output lines such as `toMap rejected null value`.