-
Enhancement
-
Resolution: Unresolved
-
P5
-
None
There are some cases where a fold-left operation is exactly what's needed. The Streams API doesn't provide this. When people go looking for foldLeft, they attempt to use reduce() in sequential mode only, but they end up writing a non-associative reduction function, which violates reduce's precondition. Or, they attempt to use a collector -- again in sequential mode only -- which in the current implementation will never call the collector's merge function. A collector has to have a merge function (it cannot be null) so they write a dysfunctional one or one that at least will throw an exception if it's called.
It's possible to write a foldLeft operation by creating a mutable container and using it to hold the intermediate values, while manipulating it from within the Consumer of forEachOrdered(). This works, but it's only slightly less contorted than using reduce() or collect() to perform a fold operation.
One problem is that foldLeft really is a left-to-right sequential operation that cannot be parallelized. However, it may be possible to parallelize upstream processing.
While we're at it, maybe add foldRight as well, though that has a somewhat different set of considerations.
It's possible to write a foldLeft operation by creating a mutable container and using it to hold the intermediate values, while manipulating it from within the Consumer of forEachOrdered(). This works, but it's only slightly less contorted than using reduce() or collect() to perform a fold operation.
One problem is that foldLeft really is a left-to-right sequential operation that cannot be parallelized. However, it may be possible to parallelize upstream processing.
While we're at it, maybe add foldRight as well, though that has a somewhat different set of considerations.
- relates to
-
JDK-8292845 The Streams API is in desperate need of folding operations
- New