java - 如何在 kotlin 中对列表进行分组和合并?
问题描述
例如,我有以下列表:
data:[
{
year:2017,
price:10
},
{
year:2017,
price:19
},
{
year:2020,
price:15
},
{
year:2021,
price:100
},
{
year:2020,
price:20
}
]
我的目的是在同一年合并列表的价格。如示例列表所示:结果需要是:
data:[
{
year:2017,
price:29
},
{
year:2020,
price:35
},
{
year:2021,
price:100
}
]
有什么方法可以快速实现吗?比如groupingby
…… map
?
解决方案
首先,您必须在所有组元素上定义grouping
一个year
聚合缩减,然后执行聚合缩减
// ListElementType is the type of objects stored in the list
yourList.groupingBy { it.year }.aggregate{key:Int, accumulator:Long?, element:ListElementType, first:Boolean ->
accumulator?.plus(element.price)?.toLong() ?: element.price.toLong()
}.toList()
推荐阅读
- xml - 使用 Google Apps 脚本将 kmz 中的数据写入工作表
- node.js - 有没有办法在谷歌云(appengine 或云功能等)上开发 websocket 客户端?
- c# - 如何在 WindowsXamlHost ListView 中添加项目?
- javascript - window.onscroll 箭头功能在 Safari 中不起作用
- python - 如何通过 2d 索引数组从 3d numpy 数组中获取项目?
- java - 收到的 JSON 与使用 Spring Rest 和 Hibernate 发送的 JSON 不同
- android - 让 Flutter 应用接受传入的意图
- python - 从 Google Cloud Functions 在 GKE 上运行的容器中执行 shell 命令
- c++ - 是否存在编译器无法诊断丢失返回的情况?
- kubernetes - 如何在普罗米修斯上获得每秒保存指标?