产品列表中产品价格的总和,关键是产品类型,价值是使用流的产品类型的价格总和

Sum of product price in Product List and key is product type and value is Sum of Prices of product type using streams

输入:产品列表。

产品 Object:id,productType,price,desc

输出:Map

key 是产品类型,value 是价格之和

假设价格是整数并且 Product class 中有合适的 getter,Collectors.groupingByCollectors.summingInt 的组合有助于解决这个任务。

Map<String, Integer> totalPriceByType = products.stream()
    .collect(Collectors.groupBy(
        Product::getProductType, 
        Collectors.summingInt(Product::getPrice)
));