简体   繁体   English

如何在kotlin中分组和合并列表?

[英]How to group and merge list in kotlin?

For example, I have the follwing list:例如,我有以下列表:

data:[
    {
        year:2017,
        price:10
    },
    {
        year:2017,
        price:19
    },
    {
        year:2020,
        price:15
    },
    {
        year:2021,
        price:100
    },
    {
        year:2020,
        price:20
    }
]

My purpose is to merge the price of list by the same year.我的目的是在同一年合并清单的价格。 As the example list show: the result need to be:如示例列表所示:结果必须是:

data:[
    {
        year:2017,
        price:29
    },
    {
        year:2020,
        price:35
    },
    {
        year:2021,
        price:100
    }
]

Is there any way to achieve it quickly?有什么办法可以快速实现吗? Like groupingby , map ...?groupingbymap ...?

First you have to define a grouping on basis of year and then perfrom a aggregation reduction on all group elements首先,您必须根据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()

I added some overhead to make this compile.我添加了一些开销来进行编译。

The essence is to group all Year-Price-Tuples by year, then reduce each group to one element (by summing up the prices).本质是按年份对所有 Year-Price-Tuples 进行分组,然后将每个组减少到一个元素(通过总结价格)。 I also added a conversion back to a list, and sorted by year.我还添加了一个转换回列表,并按年份排序。

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}") }
}

This yields:这产生:

2017: 29
2020: 35
2021: 100

You can achieve it by using this also您也可以通过使用它来实现它

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)
    }

Output will be as follows输出如下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM