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()));
相关推荐
带刺的坐椅12 分钟前
FastMCP(python)和 SolonMCP(java)的体验比较(不能说一样,但真的很像)
java·python·solon·mcp·fastmcp
一勺菠萝丶28 分钟前
深入浅出:Spring Boot 中 RestTemplate 的完整使用指南
java·spring boot·后端
努力的搬砖人.32 分钟前
Java 线程池原理
java·开发语言
有梦想的攻城狮1 小时前
SpEL(Spring Expression Language)使用详解
java·后端·spring·spel
极小狐1 小时前
如何从极狐GitLab 容器镜像库中删除容器镜像?
java·linux·开发语言·数据库·python·elasticsearch·gitlab
caihuayuan52 小时前
前端面试2
java·大数据·spring boot·后端·课程设计
黄雪超2 小时前
JVM——Java语法糖与Java编译器
java·开发语言·jvm
旷野本野2 小时前
【JavaWeb+后端常用部件】
java·开发语言
大G哥2 小时前
Rust 之 trait 与泛型的奥秘
java·开发语言·jvm·数据结构·rust
isyangli_blog2 小时前
(1-1)Java的JDK、JRE、JVM三者间的关系
java·开发语言·jvm