stream() vs. parallelStream() when adding in an ArrayList

Viewed 127

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

1 Answers

Or just:

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

This is called un-needed side effects, that are generally discouraged in the documentation.

You could keep your original code, but use a synchronized data structure (thread safe), but in this case the order of the elements is not guaranteed.

Related