如何在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…?

您也可以使用

data class Sales(
val year: Int,
val price: Int
)
fun main(args: Array<String>) {
val salesByYear = listOf(
Sales(2017, 10),
Sales(2017, 19),
Sales(2020, 15),
Sales(2021, 100),
Sales(2020, 20),
Sales(2016, 500),
Sales(2021, 320)
)

var list = ArrayList<Sales>();

salesByYear.groupBy(Sales::year).mapValues { entry ->
list.add(Sales(entry.key, entry.value.map { it.price }.sumBy { it })) }
println(list)
}

输出如下

[Sales(year=2017, price=29),
Sales(year=2020, price=35), 
Sales(year=2021, price=420), 
Sales(year=2016, price=500)]

我在编译过程中增加了一些开销。

本质是按年份对所有year - price - tuples进行分组,然后将每组减少为一个元素(通过将价格相加)。我还添加了一个转换回列表,并按年份排序。

data class Sales(val year: Int, val price: Int)
val myList = listOf(
Sales(2017, 10),
Sales(2017, 19),
Sales(2020, 15),
Sales(2021, 100),
Sales(2020, 20),
)
fun main () {
val reduced = myList.groupBy({ it.year }, { it })
.mapValues { it.value.reduce{ left, right ->
Sales(left.year, (left.price + right.price)) } }
.values
.sortedBy { it.year }
reduced.forEach { println("${it.year}: ${it.price}") }
}

这个收益率:

2017: 29
2020: 35
2021: 100

首先,您必须在year的基础上定义grouping,然后对所有组元素执行聚合约简

// 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()

最新更新