【问题标题】:Sum of product price in Product List and key is product type and value is Sum of Prices of product type using streams [closed]产品列表中的产品价格总和,键是产品类型,值是使用流的产品类型的价格总和 [关闭]
【发布时间】:2021-06-17 05:04:17
【问题描述】:

输入:产品列表。

产品对象:id,productType,price,desc

输出:地图

key是产品类型,value是价格的总和

【问题讨论】:

标签: java stream


【解决方案1】:

假设价格是整数并且Product 类中提供了适当的getter,Collectors.groupingByCollectors.summingInt 的组合有助于解决此任务。

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

【讨论】:

  • 如果确实需要 String 值,则始终可以在下游执行 collectingAndThen
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 2023-01-03
  • 2021-05-19
  • 2015-04-22
  • 2019-08-06
  • 2019-07-09
  • 1970-01-01
相关资源
最近更新 更多