I have a piece of code that I use to generate PDF document, it's simplified just to demonstrate the problem.
PdfPTable table = new PdfPTable(new float[]{ 100.0f });
List<PdfPCell> cells = new ArrayList<>();
List<String> labels = Arrays.asList(
Labels.ITEM_NAME,
Labels.QUANTITY,
Labels.PRICE
);
for (String label : labels) {
PdfPCell cell = new PdfPCell(new Phrase(label));
cells.add(cell);
}
for (PdfPCell cell : cells) {
table.addCell(cell);
}
I want to convert it to functional style with Java 8 streams.
I know that I javascript I can use reduce like this:
let container = { items: [] };
[1, 2, 3]
.reduce((container, item) => {
container.items.push(item);
return container;
}, container);
console.log(container); // { items: [ 1, 2, 3 ] }
I am trying to use same approach in Java, so my code is something like this:
PdfPTable myTable = Stream.of(
Labels.ITEM_NAME,
Labels.QUANTITY,
Labels.PRICE)
.map(s -> new PdfPCell(new Phrase(s)))
.reduce(new PdfPTable(new float[]{ 100.0f }), (table, cell) -> {
table.addCell(cell);
return table;
});
But it's not compiling because in reduce function table is recognised as cell, types do not match properly.
What I am trying to use seems to be accumulator function, this is what my IDE shows me:

From documentation:
java.util.stream.Stream public abstract T reduce(T identity, java.util.function.BinaryOperator accumulator) Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. This is equivalent to:
T result = identity;
for (T element : this stream)
result = accumulator.apply(result, element)
return result;
but is not constrained to execute sequentially. The identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t. The accumulator function must be an associative function.
All examples show primitive arithmetic operations like calculating sum and mention that these accumulator function must be stateless. I am not even sure if what I am trying to is a proper thing, please let me know.