简体   繁体   中英

How to use Switch-statement inside a Stream

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM