在ArrayList中添加时stream()与parallelStream()

car*_*era 3 parallel-processing functional-programming java-8 java-stream

我有这段代码

List<UserNotification> userNotifications = new ArrayList<UserNotification>();

teatreAlertNotifications
            .parallelStream()
            .forEach(can -> userNotifications.add(new UserNotification(can)));
Run Code Online (Sandbox Code Playgroud)

但由于ArrayList是不同步的,我认为这是不好的做法,我应该使用.stream()代替

Eug*_*ene 5

要不就:

List<UserNotification> userNotifications = teatreAlertNotifications
           .parallelStream()
           .map(UserNotification::new)
           .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

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

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

  • @carlesxuriguera它会使用那个参数......我不明白你的观点,这相当于`can - > new UserNotification(can)` (3认同)