Java8使用Stream将List转为Map的注意点
2022/3/30 9:19:44
本文主要是介绍Java8使用Stream将List转为Map的注意点,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
昨天QA同事给我提了一个Bug
,后台配置的顺序跟浏览器展示页面的顺序不一致,感觉莫名其妙,于是进行debug
追踪,模拟代码如下:
public class Example { private Long id; private String desc; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } @Override public String toString() { return "Example{" + "id=" + id + ", desc='" + desc + '\'' + '}'; } }
public class Test { public static void main(String[] args) { List<Example> list = new ArrayList<>(); for (long i = 1; i <=5; i++) { Example example = new Example(); example.setId(new Random().nextLong()); example.setDesc(String.valueOf(example.getId())); list.add(example); } list.forEach(System.out::println); System.out.println("===================="); Map<Long, List<Example>> id2ExaMap = list.stream().collect(Collectors.groupingBy(Example::getId)); id2ExaMap.forEach((id,example)->{ System.out.println("id:" + id + " ,example" + example); }); } }
运行main
方法后,控制台输出如下:
于是我的bug
就诞生了。上网查了一下,解释如下:
链接在这里
所以为了解决顺序问题,可以使用LinkedHashMap
来进行接收。
public class Test { public static void main(String[] args) { List<Example> list = new ArrayList<>(); for (long i = 1; i <=5; i++) { Example example = new Example(); example.setId(new Random().nextLong()); example.setDesc(String.valueOf(example.getId())); list.add(example); } list.forEach(System.out::println); System.out.println("===================="); //这里使用LinkedHashMap来进行接收 LinkedHashMap<Long, List<Example>> id2ExaMap = list.stream() .collect(Collectors .groupingBy(Example::getId, LinkedHashMap::new, Collectors.toList())); id2ExaMap.forEach((id,example)->{ System.out.println("id:" + id + " ,example" + example); }); } }
运行main
方法,控制台输出如下:
这篇关于Java8使用Stream将List转为Map的注意点的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?