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?

3 answers

  • answered 2018-05-16 06:07 daniu

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

  • answered 2018-05-16 06:14 Flown

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

  • answered 2018-05-16 06:24 Hadi J

    Other way could be like this:

    Map<IncomeType,BigDecimal> map = new HashMap<>();
    incomes.forEach(income ->map.merge(income.getType(),income.getAmount(),BigDecimal::add));