From the course: Java SE 21 Developer (1Z0-830) Cert Prep

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Collection and reduction, part 2

Collection and reduction, part 2 - Java Tutorial

From the course: Java SE 21 Developer (1Z0-830) Cert Prep

Collection and reduction, part 2

- Now, a pure function creates a new result for every execution. And sometimes when we do this, it's possible that memory allocation, initialization and garbage collection might become expensive. So an alternative could be to mutate an intermediate result object, and then other than with that result object, we would want to keep the operation pure, we don't want side effects going off all over the place. However, this need not be unsafe or error prone if that result object that's being mutated is kept in a tight scope and not shared. If we're using associativity to group these operations, then each group must have its own result object. Notice, we can't have a result object being messed with from multiple places at once or things could get very confusing. Similarly, a mutating aggregation will need to happen at the end of all these operations. And this type of operation is called a collection in the stream API and is…

Contents