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()));
相关推荐
极***涯2 分钟前
深度拆解:多源BFS路径重构难题——跳出单层遍历误区,搞定高阶最短路径全量解
java·重构·宽度优先
YuK.W1 小时前
Leetcode100: 70.爬楼梯、118.杨辉三角、198.打家劫舍
java·算法·leetcode
这不小天嘛1 小时前
JAVA八股——redis篇
java·开发语言·redis
聚美智数3 小时前
黄历查询-运势查询-国际法定节假日查询-API接口介绍
android·java·数据库
Yeats_Liao5 小时前
18:JavaBean简介及其在表单处理与DAO设计模式中的应用-Java Web
java·后端·架构
范什么特西5 小时前
网络代理问题
java·linux·服务器
三月不知肉味y5 小时前
2026-07-05-JAVA面试场景题训练
java·开发语言·面试
豆瓣鸡6 小时前
封装 API 请求日志切面——从注解定义到 Starter 自动装配
java·开发语言·spring boot
掉鱼的猫6 小时前
把 OpenAPI 接入 Agent Harness:零代码让 Agent 听懂你的 REST API
java·llm·agent
lzhcoder6 小时前
Spring Boot 集成 Kafka:先跑通 Demo,再避开那 80% 的人踩过的坑
java·kafka