Home > Mobile >  How to use Switch-statement inside a Stream
How to use Switch-statement inside a Stream

Time:11-30

I need to get a balance sum from a list of type List<TransactionSumView>, which I'm receiving from the database.

My TransactionSumView interface:

//projection interface
public interface TransactionSumView {
        
    String getType();
    BigDecimal getAmount();
}

Please see my implementation below:

List<TransactionSumView> listSum = transactionsRepository.findAllSumByAcc1IdGroupByType(id);
        
BigDecimal sum = BigDecimal.ZERO;

// forEach loop
for (TransactionSumView list : listSum) {
    switch (list.getType()) {
        case "E":
        case "T":
            sum = sum.subtract(list.getAmount());
            break;
        case "I":
            sum = sum.add(list.getAmount());
            break;
    }
}

How can I solve it using Stream API?

CodePudding user response:

You can use a combination of map() and reduce(identity,accumulator) operations.

BigDecimale.negate() can be applied to change the sign of a value to represent the cases when it should be subtracted.

List<TransactionSumView> listSum = transactionsRepository.findAllSumByAcc1IdGroupByType(id);
    
BigDecimal sum = listSum.stream()
    .map(sumView -> "I".equals(sumView.getType()) ?
        sumView.getAmount() : sumView.getAmount().negate()
    )
    .reduce(BigDecimal.ZERO, BigDecimal::add);
  • Related