网站首页 > 技术文章 正文
在工作中常常会遇到将List转化为Map的场景,下面总结了经常使用到的几种方式;并简单的做了简单测试,供大家学习使用。
使用Stream流将List转化为Map的几种方式
准备工作:
List<UserEntity> entityList = new ArrayList<>();
UserEntity userEntity = new UserEntity();
userEntity.setUserId("0001");
userEntity.setUserName("0001Name");
userEntity.setUserMobile("0001Phone");
entityList.add(userEntity);
UserEntity userEntity2 = new UserEntity();
userEntity2.setUserId("0002");
userEntity2.setUserName("0002Name");
userEntity2.setUserMobile("0002Phone");
entityList.add(userEntity2);
方式一:key和value都是对象中的某个属性值
key为userId、value为userName
Map<String, String> userMap1 = entityList.stream().collect(Collectors.toMap(UserEntity::getUserId, UserEntity::getUserName));
注:当userId出现重复的情况,会报 Duplicate key的错误。
方式二:key是对象中的某个属性值,value是对象本身。
key为userId、value为UserEntity对象
Map<String, UserEntity> userMap2 = entityList.stream().collect(Collectors.toMap(UserEntity::getUserId, user -> user));
另外一种写法:
Map<String, UserEntity> userMap3 = entityList.stream().collect(Collectors.toMap(UserEntity::getUserId, Function.identity()));
注:以上两种写法,当userId出现重复的情况,同样会报 Duplicate key的错误。
如果存在key重复的情况,使用第二个key去覆盖第一个key的值,写法如下:
Map<String, UserEntity> userMap4 = entityList.stream().collect(Collectors.toMap(UserEntity::getUserId, Function.identity(), (oldValue, newValue) -> newValue));
方式三:List根据key进行分组
根据userId进行分组
Map<String, List<UserEntity>> userIdGroupByList = entityList.stream().collect(Collectors.groupingBy(UserEntity::getUserId));
猜你喜欢
- 2024-10-18 【Python】map函数的常见用法,你知道多少?
- 2024-10-18 Python 中的数据可视化:将列表转换为图形
- 2024-10-18 Java 把一个 List 转换为字符串(java list转成字符串)
- 2024-10-18 Java Stream API:将线性集合添加到Map,键为对象属性
- 2024-10-18 SpringBoot读取配置文件中的数据到map和list
- 2024-10-18 「Java」咦,它就是Map和List的儿子吧
- 2024-10-18 一日一技:举例说明python中的map()方法
- 2024-10-18 详解 Python Map 函数(python map函数的用法)
- 2024-10-18 你应该知道的Java Map 的七个常见问题!
- 2024-10-18 Java核心数据结构(List、Map、Set)原理与使用技巧
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- static函数和普通函数 (76)
- el-date-picker开始日期早于结束日期 (70)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- js数组插入 (83)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)