Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading