Home > Software design >  How to get the list of values that belong to a group after groupBy operation in Kotlin?
How to get the list of values that belong to a group after groupBy operation in Kotlin?

Time:06-28

I have the following data:

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

I want to see how to get the list of values for each group. For example, I want the result as

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

CodePudding user response:

You can use the following:

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

CodePudding user response:

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

val result = myList
  .groupBy { it.year }
  .mapValues { (_, value) -> value.map { it.price } }

println(result)   // Output: {2017=[10, 19], 2020=[15, 20], 2021=[100]}
  • Related