I got the below data as example:
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:
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;
}


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