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

如何基于年月对Kotlin的Item对象值求和并生成新对象

解决Kotlin中按年月分组求和Item的问题

嗨,这个需求用Kotlin标准库的集合操作就能轻松实现,核心就是分组+求和+转换三步,下面给你具体的实现代码和解释:

实现代码

val items = listOf(
    Item(month = 1, year = 2019, value = 5000),
    Item(month = 1, year = 2019, value = 200),
    Item(month = 1, year = 2019, value = 300),
    Item(month = 1, year = 2019, value = 1000),
    Item(month = 2, year = 2019, value = 5000),
    Item(month = 2, year = 2019, value = 6000),
    Item(month = 3, year = 2019, value = 500),
    Item(month = 3, year = 2019, value = 1500),
    Item(month = 5, year = 2019, value = 900),
    Item(month = 1, year = 2020, value = 700)
)

val result = items
    // 第一步:按年和月分组,用Pair(year, month)作为唯一分组键
    .groupBy { Pair(it.year, it.month) }
    // 第二步:遍历每个分组,计算value总和并生成新Item
    .map { (key, groupItems) ->
        val (year, month) = key
        Item(month = month, year = year, value = groupItems.sumOf { it.value })
    }

代码解释

  1. 分组操作:groupBy { Pair(it.year, it.month) }会把所有year和month相同的Item归到同一个分组里,分组的key是(year, month)的Pair,确保唯一标识一组年月。
  2. 求和与转换:map遍历每个分组,先解构key得到year和month,然后用sumOf { it.value }计算当前分组内所有Item的value总和(如果你的Kotlin版本低于1.4,可以用sumBy { it.value }替代),最后创建一个新的Item对象保存结果。

运行这段代码后,result就会和你期望的完全一致啦!

内容的提问来源于stack exchange,提问作者r.n. hermann

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:31:54