Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin duplicate items in list to create a new list of different objects with the same data

I have two data structures:

data class MyObjectA(val foo: String, val barA: String, val barB: String)
data class MyObjectB(val foo: String, val bar: String)

And I have a list with MyObjectA items:

val mylistA = listOf(
    MyObjectA("aaa", "bbb", "ccc"), 
    MyObjectA("ddd", "eee", "fff")
)

I want to get a list with each object repeated, but each new item containing only some of the original data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val mylistB = listOf(
    MyObjectB("aaa", "bbb"),
    MyObjectB("aaa", "ccc"),
    MyObjectB("ddd", "eee"), 
    MyObjectB("ddd", "fff")
)

Is there some extension function in Kotlin to do it in short?

>Solution :

I would do it like this:

data class MyObjectA(val foo: String, val barA: String, val barB: String) {
    fun toB() = listOf(MyObjectB(foo, barA), MyObjectB(foo, barB))
}
data class MyObjectB(val foo: String, val bar: String)

fun main() {
    val mylistA = listOf(
        MyObjectA("aaa", "bbb", "ccc"),
        MyObjectA("ddd", "eee", "fff")
    )

    val myListB = mylistA.flatMap { it.toB() }

    println(myListB)
}

If you don’t want to add the toB() function to the data class you can of course also do it directly like

val myListB = mylistA.flatMap { listOf(MyObjectB(it.foo, it.barA), MyObjectB(it.foo, it.barB)) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading