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; } ));

相关推荐
百***581419 小时前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
全栈胖叔叔-瓜州19 小时前
关于微软最新数据库引擎sqlserver2025 关于向量距离函数调用的问题
数据库·microsoft
IDOlaoluo21 小时前
Windows系统调校_20250408_36367c06.exe安装教程(附详细步骤)
windows
视觉震撼1 天前
RDP登录事件详细溯源分析脚本(兼容Windows PowerShell版本)
运维·网络·windows·网络安全·网络攻击模型·安全威胁分析·安全架构
井上泷奈1 天前
Win键失效解决方法
windows·经验分享·其他
网硕互联的小客服1 天前
Windows2008 如何禁用FSO?
运维·服务器·网络·windows·安全
IT考试认证1 天前
微软AI-900考试认证题库
人工智能·microsoft
不惑_1 天前
[特殊字符] 在 Windows 上设置 SQLite
数据库·windows·sqlite
综合热讯1 天前
微软Office下线“重用幻灯片”功能,WPS反向升级:AI让旧功能焕新生
人工智能·microsoft·wps