I have a list of objects and each element of that list is an object that contains several BigDecimal parameters. I'm generating a new Amount object based on some calculations made on the list. It works fine but looks kind of repetitive.
new Amount()
.withAmountIncVat(invoiceLines.stream().map(line -> line.getAmount().getAmountIncVat()).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP))
.withAmount(invoiceLines.stream().map(line -> line.getAmount().getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP))
.withVatAmount(invoiceLines.stream().map(line -> line.getAmount().getVatAmount()).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP))
Is there a better way to deal with the lambda expression in order to replace the "repeated" code? You know, improve this function:
invoiceLines.stream().map(line -> line.getAmount().XXX).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP)
In which XXX should be a different BigDecimal attribute from the object each time, and i can use this function for each assignment:
new Amount()
.withVatAmount(function.apply(invoiceLines,<PERHAPS AN ADDITIONAL PARAM>))
.withAmountIncVat(function.apply(invoiceLines,<PERHAPS AN ADDITIONAL PARAM>))
.withAmount(function.apply(invoiceLines,<PERHAPS AN ADDITIONAL PARAM>))