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 分钟前
Redis(166)如何使用Redis实现实时统计?
java·redis·bootstrap
better_liang4 分钟前
每日Java面试场景题知识点之-Spring Boot微服务配置管理
java·spring boot·微服务·面试题·配置管理
seven97_top5 分钟前
数据结构——树
java·数据结构
凛冬君主6 分钟前
探索 Spring 的基础依赖与 Spring Boot 依赖
java·spring boot·spring
谷粒.7 分钟前
让缺陷描述更有价值:测试报告编写规范的精髓
java·网络·python·单元测试·自动化·log4j
lkbhua莱克瓦2412 分钟前
IO流——字符集
java·笔记·字符集·字符流
BBB努力学习程序设计18 分钟前
Java包(Package):代码的"组织管理器"
java
czc66624 分钟前
【项目实战】Redis+RabbitMQ+MySQL双阈值批量异步落库设计
java
尼古拉斯·纯情暖男·天真·阿玮31 分钟前
[JavaEE初阶] 进程和线程的区别和联系
java·开发语言