Stream.foldLeft, one more time (8133680)
Tagir F. Valeev
amaembo at gmail.com
Fri Jan 29 14:37:59 UTC 2016
Hello!
What do you think, is it still reasonable to add foldLeft operation to
JDK-9 Stream API (foldLeft only, no foldRight)?
I propose the following signatures:
interface Stream {
public <U> U foldLeft(U seed, BiFunction<U, ? super T, U> accumulator);
public Optional<T> foldLeft(BinaryOperator<T> accumulator);
}
interface IntStream {
public int foldLeft(int seed, IntBinaryOperator accumulator);
public OptionalInt foldLeft(IntBinaryOperator accumulator);
}
interface LongStream {
public OptionalLong foldLeft(LongBinaryOperator accumulator);
public long foldLeft(long seed, LongBinaryOperator accumulator);
}
interface DoubleStream {
public OptionalDouble foldLeft(DoubleBinaryOperator accumulator);
public double foldLeft(double seed, DoubleBinaryOperator accumulator);
}
They are similar to the corresponding reduce operations, but it's not
required for accumulator to be associative and it's not required for
seed to have identity properties. It should be clearly stated in
JavaDoc that for associative accumulator reduce should be used
instead.
All methods can be easily implemented as default methods in the
interfaces. For example, DoubleStream::foldLeft:
public double foldLeft(double seed, DoubleBinaryOperator accumulator) {
double[] box = new double[] { seed };
forEachOrdered(t -> box[0] = accumulator.applyAsDouble(box[0], t));
return box[0];
}
I can take this issue (if nobody works on it already), but in order
not to do the useless work I want to be sure that there are no strong
objections against such feature.
With best regards,
Tagir Valeev.
More information about the core-libs-dev
mailing list