list转map

1. List 转 Map<Integer,List>

Map<Integer, List<User>> subLineInfoMap = userInfos .stream().collect(Collectors.groupingBy(User::getSex));

2. List 转 Map<Integer,User>

Map<Long, User>userMap = userInfos.stream().collect(Collectors.toMap(User::getStuNum,Function.identity()));

3. List 转 Map<Integer,String>

Map<Integer, String> collect = userInfos.stream().collect(Collectors.toMap(User::geUserNum, User::getUserName));

4. list 转 map 保持顺序

LinkedHashMap<String, User> userMap = users.stream().collect(LinkedHashMap::new, (map, item) -> map.put(item.getAccountId(), item), Map::putAll);

5. 将list转成map 并排序

将list 排序,并按照排序后的结果进行有序分组

LinkedHashMap<String, List<AlarmData>> alarmMap = alarmDataList.stream().sorted(Comparator.comparing(t->t.getId().getData_time())).collect(Collectors.groupingBy(t->t.getId().getVirtualPointId(), LinkedHashMap::new, Collectors.toList()));

将map排序,并且每个key对应的list里面也是排序好的

6. 我们在利用Lambda 将list转成Map时就会出现 Duplicate key xxxx 的异常,意思就是对要转为map的key有重复了,除了进行for循环去重之外,我们还有其它方式能够优雅的处理它.

key重复时直接用后面的值(使用最新的或最老的值)

Map<String, Long> collect = list.stream().collect(Collectors.toMap(User::getExternalUserId, User::getUserId, (val1, val2) -> val2));

将两个值拼接起来

Map<String, Long> collect = list.stream().collect(Collectors.toMap(User::getExternalUserId, User::getUserId, (val1, val2) -> val1+val2));

将重复key的value变成一个集合,注意null值处理

Map<String, List<String>> tagMap = list.stream().collect(Collectors.toMap(User::getExternalUserId, s -> { List<String> tags = new ArrayList<>(); tags.add(s.getFollowTags()); return tags; }, (List<String> val1, List<String> val2) -> { val1.addAll(val2); return val1; } ));

相关推荐
武藤一雄3 小时前
C#:Linq大赏
windows·后端·microsoft·c#·.net·.netcore·linq
ManageEngine卓豪4 小时前
企业网站监控与性能优化指南
数据库·microsoft·性能优化
AI云原生5 小时前
openEuler软件生态体验——从桌面到服务器的全方位探索
运维·服务器·windows·macos·docker·云计算·腾讯云
JosieBook5 小时前
【IDEA】IntelliJ IDEA 快捷键大全(Windows/Linux 版)
linux·windows·intellij-idea
学习研习社5 小时前
如何在 Windows 上恢复已删除/未保存的 Excel 文件 - 5 种快速方法
windows·excel
HelloRevit6 小时前
cfapi 入门实战(二):实现云文件回传
windows
cheniie6 小时前
Windows网络共享指南
windows·ics·网络共享
初听于你8 小时前
Thymeleaf 模板引擎讲解
java·服务器·windows·spring boot·spring·eclipse
国服第二切图仔8 小时前
Electron for鸿蒙PC封装的步骤进度指示器组件
microsoft·electron·harmonyos·鸿蒙pc
MrEnginx8 小时前
解决Windows提示无法加载文件 xxx.ps1,因为在此系统上禁止运行脚本
windows