Reputation: 3628
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?
Upvotes: 8
Views: 21870
Reputation: 111
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);
Upvotes: 10
Reputation: 6706
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
Upvotes: 2
Reputation: 77206
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.
Upvotes: 3