首页 > 其他 > 详细

stream将list转化为map

时间:2021-02-23 11:08:06      阅读:186      评论:0      收藏:0      [点我收藏+]

在Stream流中将List转换为Map,是使用Collectors.toMap方法来进行转换。

1.key和value都是对象中的某个属性值。

Map<String, String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId, User::getName));

2.key是对象中的某个属性值,value是对象本身(使用返回本身的lambda表达式)。

Map<String, User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId, User -> User));

3.key是对象中的某个属性值,value是对象本身(使用Function.identity()的简洁写法)。

Map<String, User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

4.key是对象中的某个属性值,value是对象本身,当key冲突时选择第二个key值覆盖第一个key值。

Map<String, User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (oldValue, newValue) -> newValue));

如果不正确指定Collectors.toMap方法的第三个参数(key冲突处理函数),那么在key重复的情况下该方法会报出【Duplicate Key】的错误导致Stream流异常终止,使用时要格外注意这一点。

 

"管好自己,莫渡他人。"

stream将list转化为map

原文:https://www.cnblogs.com/yanggb/p/14414611.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!