List grouping and accumulate Data

105 Views Asked by At

I got the below data as example:

enter image description here

I want to group the data by Service Type, and then find the same Charge Type under the Service Type, and accumulate the amount and quantity, so that my list/map will give this outcome:

enter image description here

I used the following code:

Map<String, Map<String,ChargeType>> chargeTypeCol;
return chargeTypeCol = chargeTypeList
        .stream().collect(Collectors.groupingBy(ChargeType::getServiceType,
                                                Collectors.toMap(ChargeType::getServiceType,
                                                Function.identity(),
                                                (a, b) -> new ChargeType(b.getServiceType(), b.getChargeTypeName() ,a.getAmount() + b.getAmount(), a.getQuantity() + b.getQuantity()),
                                                LinkedHashMap::new)));

But it only return me 1 Charge Type per Service Type in the mapping.

below is the model that i have:

public ChargeType(String serviceType, String chargeTypeName, Double amount, Integer quantity) {
        this.serviceType = serviceType;
        this.chargeTypeName = chargeTypeName;
        this.amount = amount;
        this.quantity = quantity;
    }
1

There are 1 best solutions below

0
Alexander Ivanchenko On

I want to group the data by Service Type, and then find the same Charge Type

Then in the Collector toMap() you need to use getChargeTypeName() while defining a keyMapper function:

return chargeTypeList.stream()
    .collect(Collectors.groupingBy(
        ChargeType::getServiceType,
        Collectors.toMap(
            ChargeType::getChargeTypeName, // <- change the keyMapper function
            Function.identity(),
            (a, b) -> new ChargeType(b.getServiceType(), b.getChargeTypeName() ,a.getAmount() + b.getAmount(), a.getQuantity() + b.getQuantity()),
            LinkedHashMap::new
        )
    ));