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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With