实现说明
全部逻辑都在类 LabelIndex、Item和函数 main中。
转换写成 stream 链,由收集器一次性执行。
使用要点
- 演示输出是带标签的(
toMap rejected null value),每个操作都会留下自己的一行标注。
常见问题
运行「toMap 收集器的 null 值陷阱」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 toMap rejected null value 标签标明各步骤。
核心语句
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);
代码示例
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);
}
}