foldIndexed()
Perform a fold over every element in the input stream along with its index
Implementation Notes
Performs an ordered reduction over the input stream, along with the index of the element being reduced/folded. Because
this implementation produces a single result, it is probably not suitable to apply to infinite input streams. This
implementation attempts to behave like the non-indexing
Gatherers::fold()
in
the JDK. For a scanning version of this Gatherer, see scanIndexed()
.
Signature
foldIndexed(Supplier<OUTPUT> initialValue, IndexedAccumulatorFunction<OUTPUT, INPUT, OUTPUT> foldFunction)
initialValue
- A non-nullSupplier
to provide the seed value for the fold (this implementation does not assume the first element is the seed)foldFunction
-IndexedAccumulatorFunction
is a variation on aBiFunction
which injects thelong
index of each element. This function does the actual fold/reduction work.
Examples
Perform an indexed fold
This example joins the index and the input strings to show how this works.
Stream
.of("A", "B", "C", "D")
.gather(
Gatherers4j.foldIndexed(
() -> "", // initialValue
(index, carry, next) -> carry + String.format("%s%d ", next, index)
)
)
.forEach(System.out::println);
// A0 B1 C2 D3