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()));
相关推荐
敲代码的嘎仔28 分钟前
JavaWeb零基础学习Day1——HTML&CSS
java·开发语言·前端·css·学习·html·学习方法
Terio_my6 小时前
Java bean 数据校验
java·开发语言·python
超级大只老咪6 小时前
何为“类”?(Java基础语法)
java·开发语言·前端
我笑了OvO7 小时前
C++类和对象(1)
java·开发语言·c++·类和对象
weixin_436525078 小时前
Gitee - IDEA 主支 master 和分支 dev 的使用
java·ide·intellij-idea
sheji34169 小时前
【开题答辩全过程】以 YF精品视频动漫平台为例,包含答辩的问题和答案
java·eclipse
小蕾Java9 小时前
Java 开发工具,最新2025 IDEA 使用
java·ide·intellij-idea
是席木木啊9 小时前
Idea升级到2024版本:“marketplace plugins are not loaded”解决方案
java·ide·intellij-idea
胚芽鞘6819 小时前
博客标题:解密 IntelliJ IDEA 调试:当你的 List 不仅仅是 List
java·ide·intellij-idea
꒰ঌ 安卓开发໒꒱9 小时前
Java面试-并发面试(一)
java·jvm·面试