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

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

On Aug 13, 2017, at 6:27 AM, Tagir Valeev <amaembo at gmail.com> wrote:
> Please review the preliminary implementation for Stream foldLeft and
> foldRight operations:
> http://cr.openjdk.java.net/~tvaleev/webrev/8133680/r1/

I think s.foldLeft(op) is the same as s.sequential().reduce(op).
If that's the case, there's no need for it, except in documentation.

A quick, inexpert read of package-info.java suggests to me that
the encounter order of a sequential ordered stream is stable,
and therefore the result of executing a reduce on such a stream
should always produce the same order of operations.  Which
order?  Well of course, the one given in the javadoc.  Which
is an implementation of your foldLeft, minus the unnecessary

The foldRight operation is not a natural stream operation.
It needs to operate in reverse sequential order, which a stream
doesn't support.  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

To me I think foldRight belongs (and also foldLeft) in Arrays and Collections,
alongside sort.  One reason we are being slow to add that sort of thing
is because we plan to change our genericity story.

Finally, although I can't quarrel too much with Scala's choice of
terms, I find it hard to tell which is which.  (I'm also left-handed.)
Personally find foldLeft (and foldl) hard to remember, and would
prefer something that makes it clear that you are processing
elements from left to right.  So foldFromLeft would help me.
But in that case it should just be reduceFromLeft, since we already
have reduce (which means place the brackets wherever).

— John

More information about the core-libs-dev mailing list