RFR: JDK-8133680 add Stream.foldLeft() terminal operation

John Rose john.r.rose at oracle.com
Fri Aug 18 01:46:01 UTC 2017


On Aug 17, 2017, at 6:32 PM, John Rose <john.r.rose at oracle.com> wrote:
> 
> Better to make the buffering required for
> that reversal explicit to the user, IMO.  I know it's a case of
> brief notation vs. "picky" explicitness; in this case the pickiness
> wins because there is an extra O(N) copy hiding in the pretty
> brevity.

One more thought:  These concerns could be balanced by
giving Stream a reverse() operation.  Then reverse().reduce()
with a suitable lambda would give you foldRight.  The reversed
stream would be in sequential mode, of course.  Unless the
stream is already pointed at a reversible data source, the
user will know that it is an expensive operation, requiring
the original stream to be run forward into a buffer.

So:

s .foldLeft(op) == s .sequential() .reduce(op)

(Isn't the .sequential() guaranteed to be a no-op if the source
is a list or array and there is no parallel transform??)

And:

s .foldRight(op) == s .reverse() .reduce((x,y)->op.apply(y,x))

To me that seems to hit the right balance between convenience
and clarity of performance model.



More information about the core-libs-dev mailing list