【问题标题】:How to get the list of values that belong to a group after groupBy operation in Kotlin?如何在 Kotlin 中进行 groupBy 操作后获取属于某个组的值列表?
【发布时间】:2022-06-28 08:13:58
【问题描述】:

我有以下数据:

import kotlin.test.*
import java.util.*


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

我想看看如何获​​取每个组的值列表。例如,我希望结果为

{2017=[10, 19], 2020=[15, 20], 2021=[100]}

【问题讨论】:

    标签: kotlin group-by key-value


    【解决方案1】:

    您可以使用以下内容:

    import kotlin.test.*
    import java.util.*
    
    
    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.price })
        print(reduced)  //result: {2017=[10, 19], 2020=[15, 20], 2021=[100]}
    
    // further - just for understanding
        val reduced2 = myList.groupBy({ it.year } , { it})
        print(reduced2)  
        //result: 
        //{
            //2017=[Sales(year=2017, price=10), Sales(year=2017, price=19)], 
            //2020=[Sales(year=2020, price=15), Sales(year=2020, price=20)], 
            //2021=[Sales(year=2021, price=100)]
        //}
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2017-06-30
      • 2021-11-18
      • 2014-08-04
      相关资源
      最近更新 更多