首页 > 解决方案 > 如何在 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

标签: javaandroidkotlin

解决方案


首先,您必须在所有组元素上定义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()

推荐阅读