Adding up BigDecimals using Streams Adding up BigDecimals using Streams java java

Adding up BigDecimals using Streams


Original answer

Yes, this is possible:

List<BigDecimal> bdList = new ArrayList<>();//populate listBigDecimal result = bdList.stream()        .reduce(BigDecimal.ZERO, BigDecimal::add);

What it does is:

  1. Obtain a List<BigDecimal>.
  2. Turn it into a Stream<BigDecimal>
  3. Call the reduce method.

    3.1. We supply an identity value for addition, namely BigDecimal.ZERO.

    3.2. We specify the BinaryOperator<BigDecimal>, which adds two BigDecimal's, via a method reference BigDecimal::add.

Updated answer, after edit

I see that you have added new data, therefore the new answer will become:

List<Invoice> invoiceList = new ArrayList<>();//populateFunction<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());BigDecimal result = invoiceList.stream()        .map(totalMapper)        .reduce(BigDecimal.ZERO, BigDecimal::add);

It is mostly the same, except that I have added a totalMapper variable, that has a function from Invoice to BigDecimal and returns the total price of that invoice.

Then I obtain a Stream<Invoice>, map it to a Stream<BigDecimal> and then reduce it to a BigDecimal.

Now, from an OOP design point I would advice you to also actually use the total() method, which you have already defined, then it even becomes easier:

List<Invoice> invoiceList = new ArrayList<>();//populateBigDecimal result = invoiceList.stream()        .map(Invoice::total)        .reduce(BigDecimal.ZERO, BigDecimal::add);

Here we directly use the method reference in the map method.


This post already has a checked answer, but the answer doesn't filter for null values. The correct answer should prevent null values by using the Object::nonNull function as a predicate.

BigDecimal result = invoiceList.stream()    .map(Invoice::total)    .filter(Objects::nonNull)    .filter(i -> (i.getUnit_price() != null) && (i.getQuantity != null))    .reduce(BigDecimal.ZERO, BigDecimal::add);

This prevents null values from attempting to be summed as we reduce.


You can sum up the values of a BigDecimal stream using a reusable Collector named summingUp:

BigDecimal sum = bigDecimalStream.collect(summingUp());

The Collector can be implemented like this:

public static Collector<BigDecimal, ?, BigDecimal> summingUp() {    return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);}