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

相关推荐
qq_369224335 天前
Windows全系通用!ntdll.dll文件丢失、报错、闪退问题的完整排查与修复教程
windows·dll·dll修复·dll丢失·dll错误
Data-Miner5 天前
大语言模型+智能体AI,122页PPT详解落地应用培训!
人工智能·microsoft·语言模型
阿米亚波5 天前
【Windows】QEMU 启动 openEuler aarch64/arm64 架构系统 + 离线软件源
linux·windows·经验分享·笔记·架构·arm
caimouse5 天前
Reactos 第 10 章 网络操作 — 10.3.1 NIC驱动
网络·windows
初圣魔门首席弟子5 天前
Node.js 详细介绍(知识库版)
windows·qt·node.js·知识库
c++之路5 天前
备忘录模式(Memento Pattern)
c++·microsoft
CHENG-JustDoIt5 天前
AI工具 | 爆火开源项目Odysseus AI 工作台:从项目介绍、部署情况及其使用等多方位分析指南(含详细步骤)
大数据·人工智能·windows·python·ai·开源·github
Solis程序员5 天前
MCP (Model Context Protocol):AI应用连接外部世界的标准协议
人工智能·microsoft·agent·skill·mcp
kingbal5 天前
Windows:flutter环境搭建
windows·flutter
诺未科技_NovaTech5 天前
上海诺未携手惠灵顿中国,基于微软 Azure 打造 AI 教育生态标杆
人工智能·microsoft·azure·ai教育