Sum List of BigDecimal

12,293

Solution 1

Here is a way to do it with only Java 8 and streams:

List<BigDecimal> list = Arrays.asList(new BigDecimal(10.333), //
   new BigDecimal(14.333));
BigDecimal result = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

Solution 2

If you can't use Java 8 lambdas or Groovy closures, in which case you could write a one-liner to replace your four lines, the code you have is thoroughly clear. Using a library-based iteration tool will almost certainly make the code more complicated and will certainly make it slower. You made it about as simple as it gets; it's fine.

Solution 3

If you don't mind the extra third-party library dependency, then there is a solution for this problem in Eclipse Collections.

List<BigDecimal> list =
    Lists.mutable.with(
        new BigDecimal("10.333"),
        new BigDecimal("14.333"));

Assert.assertEquals(
    new BigDecimal("24.666"),
    Iterate.sumOfBigDecimal(list, Functions.getPassThru()));

Since you have a list of BigDecimal already, the function that is applied to each just passes the value through.

Note: I am a committer for Eclipse Collections

Share:
12,293
AJJ
Author by

AJJ

Loves to Code. Loves to learn new technology and frameworks. Likes Web development the most.

Updated on August 16, 2022

Comments

  • AJJ
    AJJ over 1 year

    I am working on a project with Spring and Maven and Java 7.

    I have a list with bigdecimal and have to sum up all the elements in the list. i know using for loop we can to as below,

    List<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal(10.333));
    list.add(new BigDecimal(14.333));
    BigDecimal result = new BigDecimal(0);
    for (BigDecimal b : list) {
         result = result.add(b);
    }
    

    Is there a better way to do? using google gauva FluentIterable or apache ArrayUtils/StatUtils?

  • Holger
    Holger over 8 years
    Exactly. Well, replacing the initial value new BigDecimal(0) with BigDecimal.ZERO, but that’s it. Nothing more to improve…