Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8133680

add Stream.foldLeft() terminal operation

    Details

    • Type: Enhancement
    • Status: Open
    • Priority: P5
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: tbd
    • Component/s: core-libs
    • Labels:

      Description

      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.

        Attachments

          Activity

            People

            • Assignee:
              smarks Stuart Marks
              Reporter:
              smarks Stuart Marks
            • Votes:
              1 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated: