Current approach based on double type of product prize.
public Map<String, BigDecimal> averageProductPriceInCategory() {
return shopping.entrySet()
.stream()
.flatMap(e -> e.getValue().keySet().stream())
.collect(Collectors.groupingBy(Product::getCategory,
Collectors.averagingDouble(Product::getPrize)));
}
shopping is basically a map: Map<Client, Map<Product,Integer>>
,
- The outer Key represents the Client
- The inner Key represents the Product. Product class members are name, category, price (previously of double type) - want to refactor the provided code into one using price as a type of BigDecimal
- the inner maps value (Integer) reprents the number of specified product which belong to a specific client
Below snippet can be used only for calculating the total prize of products which belong to a specified category. Not sure, how to calculate the average products prize in regards to category with using BigDecimals
Map<String, BigDecimal> totalProductPriceInEachCategory = shopping.entrySet().stream()
.flatMap(e -> e.getValue().keySet().stream())
.collect(Collectors.groupingBy(Product::getCategory,
Collectors.mapping(Product::getPrize,
Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));