Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 472
carles xuriguera Avatar asked May 20 '26 07:05

carles xuriguera


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.

like image 83
Eugene Avatar answered May 22 '26 17:05

Eugene