Collectors.toMap / list 转 map

前言

略

Collectors.toMap

java 复制代码
List<User> userList = ...;
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));

假如id存在重复值,则会报错Duplicate key xxx, 解决方案

两个重复id中,取后一个:

java 复制代码
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity(),(oldValue,newValue) -> newValue));

两个重复id中,取前一个:

java 复制代码
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity(),(oldValue,newValue) -> oldValue));

转 id 和 name

java 复制代码
Map<Long, String> map = userList.stream().collect(Collectors.toMap(User::getUserId, User::getName)); 

name 为 null 的解决方案:

java 复制代码
Map<Long, String> map = userList.stream().collect(Collectors.toMap(Student::getUserId, e->e.getName()==null?"":e.getName()));
相关推荐
w_zero_one5 分钟前
链表(2)
java·数据结构·链表
白杨尚青12 分钟前
C++入门篇(十一):string(中)——容量与增删改查:一篇吃透所有常用接口(万字详解)
java·开发语言·c++
SimonKing23 分钟前
SSE、WebSocket 连接丢 Redis 里?那可踩大坑了!
java·后端·程序员
倔强的石头10627 分钟前
【Linux指南】动静态库系列(九):动态库如何进入进程地址空间:从磁盘 .so 到共享内存映射
java·linux·服务器
TeamDev34 分钟前
JxBrowser 9.5.2 版本发布啦!
java·前端·windows·chromium·混合应用·jxbrowser·浏览器控件
鬼手点金35 分钟前
Claude Code示范案例-进阶学习路径
java·服务器·前端·学习·计算机视觉·前向传播
浪子明X37 分钟前
用 CMake Presets 固定跨平台构建:从本地开发到 CI 的依赖一致性实践
java·spring·ci/cd
苏supper1 小时前
记一次Nacos鉴权报错unknown user,403排查|SecurityProxy源码,fastjson2扩展包缺失
java·后端
\光辉岁月/1 小时前
6.mybatisplus学习-BaseMapper、Service、常用注解
java·mybatis·mybatisplus
微信开发api1 小时前
基于WTAPI构建社群运营平台:自动拉群与会话承接链路设计
java·大数据·网络·数据库·微信·自动化