简体   繁体   中英

Collecting to map using Java Stream API

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 bigDecimals. How can I do it using Java Stream API?

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

You can use Collectors.toMap to collect as Map

Map<LocalDate, BigDecimal> res = 
      list.stream()
          .collect(Collectors.toMap(Balance::getDate, Balance::getValue, 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