Home > database >  Create multiple object lists from one, based on an object parameter in Kotlin
Create multiple object lists from one, based on an object parameter in Kotlin

Time:04-06

I Have a list of object with an Int attribute, like this:

List
id: 1
id: 1
id: 2
id: 2
id: 3

and i want to create different list based on that attribute, like this:

List A List B List C
id: 1 id: 2 id: 3
id: 1 id: 2

i found some ways to do it but i wanted to know if there was an efficient way, maybe using some method that kotlin already provide.

CodePudding user response:

data class Test(
  val id: Int,
  val text: String
)

val list = listOf(
  Test(1, "a"),
  Test(1, "b"),
  Test(2, "c"),
  Test(2, "d"),
  Test(3, "e")
)

val result = list
  .groupBy { test -> test.id }
  .map { it.value }

result.forEach(::println)

Output:

[Test(id=1, text=a), Test(id=1, text=b)]
[Test(id=2, text=c), Test(id=2, text=d)]
[Test(id=3, text=e)]

CodePudding user response:

What you want is the groupBy: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html

It will return a map, that the key is the property value that you used to group by, and the value is the list.

  • Related