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()));
相关推荐
独行soc12 分钟前
2025年渗透测试面试题总结-某华为面试复盘 (题目+回答)
java·python·安全·web安全·面试·职场和发展·红蓝攻防
neoooo17 分钟前
Redis 缓存击穿、穿透、雪崩问题及解决方案
java·spring boot·redis
web1508541593522 分钟前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
半聋半瞎23 分钟前
Java单例模式中的饿汉模式和懒汉模式
java·javascript·单例模式
小王C语言29 分钟前
【C++初阶】---类和对象(上)
java·开发语言·c++
bing_15839 分钟前
Nacos 项目是如何使用Maven 构建的?如何进行编译和打包?
java·服务发现
浅念同学1 小时前
JavaEE-MyBatis概述&第一个程序
java·java-ee·mybatis
kkk哥1 小时前
基于springboot的校园资料分享平台(048)
java·spring boot·后端
A22742 小时前
Netty——BIO、NIO 与 Netty
java·netty·nio
椒哥2 小时前
Jackson反序列化多态类型绑定
java·后端·spring cloud