首页 > 解决方案 > 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

标签: java-8parallel-processingfunctional-programmingjava-stream

解决方案


要不就:

List<UserNotification> userNotifications = teatreAlertNotifications
           .parallelStream()
           .map(UserNotification::new)
           .collect(Collectors.toList());

这称为不需要的副作用,通常在文档中不鼓励这样做。

您可以保留原始代码,但使用同步数据结构(线程安全),但在这种情况下,不能保证元素的顺序。


推荐阅读