You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java Stream对List按type分组并聚合求和

按Type分组并求和Price与Count的实现方案

嘿,这个按type分组并对price、count分别求和的需求很常见,用JavaScript的Array.reduce()方法就能轻松搞定!下面是具体的实现代码和思路解析:

代码实现

// 原始列表
const originalList = [
  { type: "1", price: 10.0, count: 2 },
  { type: "1", price: 15.0, count: 3 },
  { type: "2", price: 20.0, count: 2 },
  { type: "2", price: 30.0, count: 3 }
];

// 分组求和处理
const groupedList = Object.values(originalList.reduce((acc, currentItem) => {
  // 检查当前type是否已在累加器中存在分组
  if (!acc[currentItem.type]) {
    // 不存在则初始化一个新的分组条目
    acc[currentItem.type] = {
      type: currentItem.type,
      price: 0,
      count: 0
    };
  }
  // 对当前分组的price和count进行累加
  acc[currentItem.type].price += currentItem.price;
  acc[currentItem.type].count += currentItem.count;
  
  return acc;
}, {})); // 初始累加器为一个空对象

// 输出结果
console.log(groupedList);
// 预期输出: [{ type: "1", price: 25.0, count: 5 }, { type: "2", price: 50.0, count: 5 }]

思路解析

  • 使用reduce做累加分组:reduce方法非常适合这种需要遍历并累加聚合的场景,它会遍历原始列表的每一个元素,通过累加器(acc)逐步构建分组结果。
  • 按type创建分组键:我们用type作为累加器对象的键,确保每个type只会对应一个分组条目。
  • 累加对应字段值:如果当前type的分组已存在,就直接累加price和count;如果不存在,就先初始化一个新的分组条目,再进行累加。
  • 转换为目标数组:最后用Object.values()把累加器对象中的所有值提取出来,转换成我们需要的数组格式。

内容的提问来源于stack exchange,提问作者nirvair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:50:34