Search code examples
androidlistkotlinandroid-recyclerviewflatmap

How to flatten List of Lists in Kotlin?


I have a list of objects of class AA that contain a date and a list of objects of class BB:

data class AA(
    val date: LocalDate,
    val bb: List<BB>
)

@Parcelize
data class BB(
    val x: Int,
    val y: String,
    val z: String
) : Parcelable

I want to create a single List (flatten List<AA>) that will look like this:

 listOf(
    date obj
    BB obj
    BB obj
    date obj
    BB obj
    date obj
    BB obj
    BB obj 
    BB obj)

Instead of:

 listOf(
    date obj, listOf(BB obj, BB obj)
    date obj, listOf(BB obj)
    date obj, listOf(BB obj, BB obj, BB obj))

I tried using flatMap, but I only manage to flatten one part - BB.
How to crate a list with date and BB items?


Solution

  • As answered by @DYS you can and should use flatten to flatten a list. My answer covers how to achieve the special case stated in the question.

    You can do it this way:

    val a = listOf(
        AA(LocalDate.now(), listOf(BB(1, "1", "1")))
    )
    val flattened = a.flatMap { aa -> mutableListOf<Any>(aa.date).also { it.addAll(aa.bb) }}
    

    see complete example

    Basically you use flatMap, create a MutableList<Any> with the date and then addAll items of BB in the also block. Probably there is a more elegant way to do it but this one came to me first.

    Simply using flatten does not work here, because AA does not implement iterable.