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

相关推荐
tjsoft21 小时前
设置 windows nginx.exe 每天 重启
运维·windows·nginx
读书读傻了哟21 小时前
Windows 10 使用 VMware Workstation 搭建 Ubuntu 虚拟机
linux·windows·ubuntu
小龙报1 天前
《彻底理解C语言指针全攻略(3)》
c语言·开发语言·windows·git·创业创新·学习方法·visual studio
IDOlaoluo1 天前
Microsoft.NET安装步骤详解(.NET Framework/.NET 6/7/8安装教程)
microsoft·.net
00后程序员张1 天前
Windows 安全分割利器:strtok_s () 详解
windows·单片机·安全
NEFU AB-IN2 天前
在 Windows PowerShell(pwsh)中配置 Oh My Posh + Conda 环境美化与性能优化
windows·conda
WTCLLB2 天前
Win10,在ESP分区添加PE系统,隐藏VTOYEFI分区
windows·ventoy·bcd·wepe
E_ICEBLUE2 天前
Python 处理 Word 文档中的批注(添加、删除)
开发语言·python·microsoft·word
2501_929382652 天前
电视盒子助手开心电视助手 v8.0 删除电视内置软件 电视远程控制ADB去除电视广告
android·windows·adb·开源软件·电视盒子
CodeCraft Studio2 天前
如何从 FastReport .NET 将报表导出为 JPEG / PNG / BMP / GIF / TIFF / EMF
windows·.net·报表开发·报表工具·fastreport·报表转图片