简体   繁体   中英

Grouping and adding up BigDecimals using Java Stream API

I have a list of Income objects. Each of them has a type . I want to group them and sum up the amount field.

For this case:

Income income1 = new Income();
income1.setType(IncomeType.COMMON);
income1.setAmount(BigDecimal.valueOf(1000));

Income income2 = new Income();
income2.setType(IncomeType.COMMON);
income2.setAmount(BigDecimal.valueOf(2000));

Income income3 = new Income();
income3.setType(IncomeType.MARCIN);
income3.setAmount(BigDecimal.valueOf(100));

List<Income> incomes = Arrays.asList(income1, income2, income3);

The expected output would be a map Map<IncomeType, BigDecimal> with two elements: <COMMON, 3000> and <MARCIN, 100>

How to achieve it with Java Stream API?

Simplest solution would be using Collectors::toMap including the merge function.

Map<IncomeType, BigDecimal> grouping = incomes.stream()
    .collect(Collectors.toMap(Income::getType, Income::getAmount, BigDecimal::add));

The grouping is done by groupingBy , which allows a "downstream collector" that can do the summing.

incomes.stream()
    // to map, you say?
    .collect(Collectors.groupingBy(Income::getType, 
        // add the big integers
        Collectors.reducing(BigDecimal.ZERO, Income::getAmount, BigDecimal::add)));

Other way could be like this:

Map<IncomeType,BigDecimal> map = new HashMap<>();
incomes.forEach(income ->map.merge(income.getType(),income.getAmount(),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