winterisComing
winterisComing

Reputation: 233

Java 8 groupBy and reduce not summing up values in the column

I am trying to use Java8 groupby and reduce feature to sum elements based on grouping but the code doesnt seem to be working for me.

Here is my data from the Dtolist that I am trying to map and extract in an excel sheet. enter image description here

My requirement is that for every DTO object I want this kilometersNumber to be summed up based on groupingBy TruckId. So , the highlighted columns should be having summed up values for same TruckId(**Contract flotte)

This is my DTO:

'''public class CostsTruckWsDTO implements Serializable {

private static final long serialVersionUID = 1L;

private String truckId;

private LocalDate period;

private Bigdecimal KilometersNumber;

private String periodStartDate;

Here is the logic:: ''costsTruckWsDTO.setGroupBy(TruckId.toUpperCase());

Map<String, List> mapCostsTruck = costsTruck.stream() .collect(Collectors.groupingBy(d -> d.getGroupBy().toUpperCase())); for (Map.Entry<String, List> entry : mapCostsTruck.entrySet()) {

        BigDecimal totalKm = entry.getValue().stream().map(x -> x.getKilometersNumber()).reduce(BigDecimal.ZERO,
                BigDecimal::add);

} }''

But what am getting is value for kilometere is not geeting added as per the screenshot. Can anybody pls help me what I am missing here!!! Highly appreciate

Upvotes: 0

Views: 146

Answers (1)

Shmulik Klein
Shmulik Klein

Reputation: 3914

You can do the operation of grouping together with the operation of summing using two collectors:

Map<String, BigDecimal> result = trucks.stream()
               .collect(Collectors.groupingBy(CostsTruckWsDTO::getTruckId, 
                      Collectors.mapping(CostsTruckWsDTO::getKilometersNumber, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));

Upvotes: 0

Related Questions