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()代替
要不就:
List<UserNotification> userNotifications = teatreAlertNotifications
.parallelStream()
.map(UserNotification::new)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
这称为不需要的副作用,通常在文档中不鼓励.
您可以保留原始代码,但使用同步数据结构(线程安全),但在这种情况下,不保证元素的顺序.