Search code examples
javajava-stream

Collecting to map using Java Stream API, with map values equal to the sum of BigDecimal values for the key


Here is my class objects of I need to collect:

public class InvestBalance {

    @JsonValue
    private List<Balance> balances;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Balance {

        @JsonFormat(pattern = "yyyy-MM-dd")
        private LocalDate date;

        private BigDecimal value;
    }
}

I got a List<InvestBalance.Balance> from a database, and I need to group them by the date field, so I need to get a Map<LocalDate, BigDecimal>. Value must be a sum of BigDecimal values.

How can I do it using Java Stream API?


Solution

  • list.stream()
       .collect(Collectors.groupingBy(Balance::getDate,
                           Collectors.mapping(Balance::getValue, 
                                      Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)));
    

    Or with a static import of Collectors.* to make it more readable:

    list.stream()
       .collect(groupingBy(Balance::getDate, 
                        mapping(Balance::getValue, reducing(BigDecimal.ZERO, BigDecimal::add)));