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

Income income2 = new Income();

Income income3 = new Income();

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.
        // to map, you say?
            // 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 =
        .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));