当前位置: 首页 > news >正文

Collectors.toMap / list 转 map

前言

Collectors.toMap

List<User> userList = ...;
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));

假如id存在重复值,则会报错Duplicate key xxx, 解决方案

两个重复id中,取后一个:

Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity(),(oldValue,newValue) -> newValue));

两个重复id中,取前一个:

Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity(),(oldValue,newValue) -> oldValue));

转 id 和 name

Map<Long, String> map = userList.stream().collect(Collectors.toMap(User::getUserId, User::getName)); 

name 为 null 的解决方案:

Map<Long, String> map = userList.stream().collect(Collectors.toMap(Student::getUserId, e->e.getName()==null?"":e.getName()));

相关文章:

  • Qt桌面客户端跨平台开发实例
  • Docker搭建Testlink教程
  • 百度SEO和必应SEO优化方法
  • Java安全-类的动态加载
  • Agent系列——agent领域的mcp协议讲解
  • 如何开发一个你自己的springboot-starter
  • 自动化测试中使用的设计模式
  • 设计模式之单例模式(Singleton Pattern)
  • Kafka--常见问题
  • python-selenium 爬虫 由易到难
  • Linux实时内核 - 启用 RCU(Read-Copy Update)机制的性能测试功能
  • Excel中如何自动计算累计销量,当具体销量为空时公式自动不计算
  • 2025-03-22 学习记录--C/C++-PTA 习题4-11 兔子繁衍问题
  • 2025新版懒人精灵零基础安装调试+lua基础+UI设计交互+常用方法封装+项目实战+项目打包安装板块-视频教程(初学者必修课)
  • Linux中动静态库的创建与原理
  • Electron Forge【实战】桌面应用 —— AI聊天(上)
  • 遨游三防 | IP68热成像三防平板,助力电力智慧巡检
  • git推送代码相关学习——(一)
  • Flutter中常用命令
  • 区块链(Blockchain)—— 概念、架构与应用
  • 梵蒂冈选出新教皇,外交部:望新教皇推动中梵关系不断改善
  • 晋级中部非省会第一城,宜昌凭什么
  • 复旦设立新文科发展基金,校友曹国伟、王长田联合捐赠1亿元
  • 8小时《大师与玛格丽特》:长度可以是特点,但不是价值标准
  • 安顺市原副市长、市公安局原局长顾长华任贵州省民委副主任
  • 哈马斯官员:进一步停火谈判毫无意义