关于java8里边Collectors.toMap()的空限制

在使用stream操作把list转为map的时候报了一个NPE,但是实际上HashMap是支持key或者value为null的,很是疑惑,查了一下发现是java8设计时候的一个限制。

java 复制代码
Map<Long, Long> exportStoreSupervisorIdMap = exportStoreList.stream().collect(Collectors.toMap(PhysicalStorePO::getId, PhysicalStorePO::getSupervisorId, (K1, K2) -> K1));

有一个对象的supervisorId是null,结果npe了。

这是因为在使用 Collectors.toMap() 时,如果值为 null,会抛出 NullPointerException。这是 Java 8 的一个限制。

有几种解决方案:

1.使用 Collectors.toMap 的另一个重载方法,显式指定 HashMap::new

java 复制代码
Map<Long, Long> exportStoreSupervisorIdMap = exportStoreList.stream()
    .collect(Collectors.toMap(
        PhysicalStorePO::getId,
        PhysicalStorePO::getSupervisorId,
        (k1, k2) -> k1,
        HashMap::new
    ));

2.先过滤掉 null 值

java 复制代码
Map<Long, Long> exportStoreSupervisorIdMap = exportStoreList.stream()
    .filter(store -> store.getSupervisorId() != null)
    .collect(Collectors.toMap(
        PhysicalStorePO::getId,
        PhysicalStorePO::getSupervisorId,
        (k1, k2) -> k1
    ));

3.使用普通的 for 循环

java 复制代码
Map<Long, Long> exportStoreSupervisorIdMap = new HashMap<>();
for (PhysicalStorePO store : exportStoreList) {
    exportStoreSupervisorIdMap.put(store.getId(), store.getSupervisorId());
}

4.使用自定义的收集器方法

java 复制代码
Map<Long, Long> exportStoreSupervisorIdMap = exportStoreList.stream()
    .collect(HashMap::new,
        (map, store) -> map.put(store.getId(), store.getSupervisorId()),
        HashMap::putAll);

推荐使用第 1 或第 2 种方案,取决于你是否需要保留 null 值:

如果需要保留 null 值,使用方案 1

如果不需要 null 值,使用方案 2

这个问题的根本原因是 Collectors.toMap 的实现不支持 null 值,这是一个设计决定。如果你确实需要包含 null 值,最好明确指定使用 HashMap 作为实现。

相关推荐
huihuihuanhuan.xin几秒前
后端八股之消息队列
java·rabbitmq
渡我白衣9 分钟前
C++世界的混沌边界:undefined_behavior
java·开发语言·c++·人工智能·深度学习·语言模型
88Ra11 分钟前
Spring Boot 3.3新特性全解析
java·spring boot·后端
剑海风云24 分钟前
JDK 26:HTTP/3 支持已可在 HTTP 客户端 API 中使用
java·开发语言·http
好学且牛逼的马26 分钟前
【SSM框架 | day24 spring IOC 与 DI】
java·后端·spring
朝新_29 分钟前
【SpringBoot】配置文件
java·spring boot·笔记·后端·spring·javaee
清心歌1 小时前
Spring AI Alibaba 【四】
java·后端
不光头强1 小时前
springDI注入
java·开发语言
老华带你飞1 小时前
动漫资讯|基于Springboot的动漫交流网站设计与实现(源码+数据库+文档)
java·数据库·spring boot·后端·论文·毕设·国产动漫网站
rengang661 小时前
105-Spring AI Alibaba Module RAG 使用示例
java·人工智能·spring·rag·spring ai·ai应用编程