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()));
相关推荐
q***649716 分钟前
Spring BOOT 启动参数
java·spring boot·后端
百***784520 分钟前
Java实战:Spring Boot application.yml配置文件详解
java·网络·spring boot
你不是我我29 分钟前
【Java 开发日记】SQL 语句左连接右连接内连接如何使用,区别是什么?
java·javascript·数据库
七夜zippoe1 小时前
Java性能调优工具篇:JMH基准测试与Profiler(JProfiler/Async-Profiler)使用指南
java·开发语言·jprofiler·jmh·async-profiler
從南走到北1 小时前
JAVA国际版二手车交易二手车市场系统源码支持Android+IOS+H5+APP
android·java·ios
Kuo-Teng1 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
北i1 小时前
TiDB 关联子查询去关联优化实战案例与原理深度解析
java·数据库·sql·tidb
Kuo-Teng1 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
我命由我123451 小时前
Java 开发 - 粘包处理器 - 基于消息头 + 消息体(魔数验证、长度验证)
java·网络·后端·网络协议·java-ee·intellij-idea·intellij idea
2301_800399721 小时前
stm32 printf重定向到USART
java·stm32·算法