daydreamer
daydreamer

Reputation: 91999

Collections.forEach: How to add up values?

I have List<Transaction> where Transaction has amount as BigDecimal.

I want to add up all the amount in this list. I do something as

BigDecimal spent = new BigDecimal("0.0");
transactions.forEach(t -> spent.add(t.getAmount()));
System.out.println(spent);

When I run this, spent turns out to be 0.0

Also, syntactically transactions.forEach(t -> spent = spent.add(t.getAmount())); throws compilation errors.

I am trying to learn doing it without using for each loop

Ideas?

Upvotes: 0

Views: 239

Answers (2)

İlker Korkut
İlker Korkut

Reputation: 3250

Try streams instead of foreach

    List<BigDecimal> list = new ArrayList<>();

    list.add(new BigDecimal(10));
    list.add(new BigDecimal(10));
    list.add(new BigDecimal(10));
    BigDecimal total = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

    System.out.println(total);

Upvotes: 1

daydreamer
daydreamer

Reputation: 91999

After reading up on Adding up BigDecimals using Streams , I found out that the following is what I needed

final Function<Transaction, BigDecimal> transactionAmountMapper = Transaction::getAmount;
final BigDecimal result = entry.getValue().stream().map(transactionAmountMapper).reduce(BigDecimal.ZERO, BigDecimal::add);

Upvotes: 3

Related Questions