Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum List of BigDecimal

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?

like image 236
AJJ Avatar asked Oct 16 '15 10:10

AJJ


2 Answers

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);
like image 64
Daniel Beck Avatar answered Sep 22 '22 12:09

Daniel Beck


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.

like image 21
chrylis -cautiouslyoptimistic- Avatar answered Sep 21 '22 12:09

chrylis -cautiouslyoptimistic-