java-8 - stream() vs. parallelStream() when adding in an ArrayList
问题描述
I had this piece of code
List<UserNotification> userNotifications = new ArrayList<UserNotification>();
teatreAlertNotifications
.parallelStream()
.forEach(can -> userNotifications.add(new UserNotification(can)));
But since ArrayList is unsynchronized I think it is bad practice and I should use .stream() instead
解决方案
要不就:
List<UserNotification> userNotifications = teatreAlertNotifications
.parallelStream()
.map(UserNotification::new)
.collect(Collectors.toList());
这称为不需要的副作用,通常在文档中不鼓励这样做。
您可以保留原始代码,但使用同步数据结构(线程安全),但在这种情况下,不能保证元素的顺序。
推荐阅读
- angularjs - 无法让 Angular 应用程序在布局的 MVC 视图中工作
- algorithm - 在时间复杂度方面采用最佳方法从字符矩阵形成字符串的方法有多少?
- javascript - Gatsby:使用MDX时索引页“/”加载失败,其他路径加载
- android - 我的自定义 RecyclerView 适配器有什么错误?
- java - 示例:使用 Volley 以编程方式发送 sendgrid 电子邮件
- csv - 同时创建和编写两个CSV golang
- c# - 我对这段代码的理解是否正确/完整?
- wordpress - 在woocommerce中购买后如何在特定时间内免费提供相同的产品?
- angular - 材质按钮大小响应
- node.js - Nest.js 在生产中运行 main.js 时抛出错误