【Java 8 新特性】Map转成List
一、使用Lambda表达式将Map转化成List
在Collectors.toList()方法中使用lambda表达式将Map转换为List,如下示例
1 | List<String> valueList = map.values().stream().collect(Collectors.toList()); |
放入List之前对值进行排序:
1 | List<String> sortedValueList = map.values().stream().sorted().collect(Collectors.toList()); |
使用给定的比较器(Comparator.comparing()):
1 2 3 4 | List<BaselinePointVo> tmp = stringIntegerMap.entrySet().stream() .sorted(Comparator.comparing(e -> e.getKey())) .map(e -> new BaselinePointVo(e.getKey(), e.getValue())) .collect(Collectors.toList()); |
这里的 BaselinePointVo 是一个接收数据的类。使用Map.Entry获取Map的键和值如下:
1 2 3 4 | List<BaselinePointVo> tmp = stringIntegerMap.entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getValue)) .map(e -> new BaselinePointVo(e.getKey(), e.getValue())) .collect(Collectors.toList()); |
作为比较,也可以使用Map.Entry.comparingByValue()和Map.Entry.comparingByKey()分别根据值和键对数据进行排序:
1 2 3 4 | List<BaselinePointVo> tmp = stringIntegerMap.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .map(e -> new BaselinePointVo(e.getKey(), e.getValue())) .collect(Collectors.toList()); |
二、Map中的键或值转化成List示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | --Map中的值转换为List List<String> valueList = map.values().stream().collect(Collectors.toList()); valueList.forEach(n -> System.out.println(n)); --Map中的值转换为List并排序 List<String> sortedValueList = map.values().stream() .sorted().collect(Collectors.toList()); sortedValueList.forEach(n -> System.out.println(n)); --Map中的键转换为List List<Integer> keyList = map.keySet().stream().collect(Collectors.toList()); keyList.forEach(n -> System.out.println(n)); --Map中的键转换为List并排序 List<Integer> sortedKeyList = map.keySet().stream() .sorted().collect(Collectors.toList()); sortedKeyList.forEach(n -> System.out.println(n)); |
三、Map转化成List<T>示例
1 2 3 | List<BaselinePointVo> list =stringIntegerMap.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey())) .map(e -> new BaselinePointVo(e.getKey(), e.getValue())).collect(Collectors.toList()); list.forEach(l -> System.out.println( "Name " + l.getName()+ ", Y: " + l.getY())); |
如果需要按键来排序的话,可以使用键来排序
1 | Comparator.comparing(e -> e.getValue()) |
本文作者:IIIID
本文链接:https://www.cnblogs.com/Oxyy/p/15776067.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
Java学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下