How to flatten List of Lists in Kotlin?

user990635 picture user990635 · Aug 5, 2019 · Viewed 11.4k times · Source

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?

Answer

DYS picture DYS · Sep 20, 2019

The simplest one I know of is the extension flatten() function to Iterable. Since List is a subclass of the latter, it is applicable.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/flatten.html

val deepList = listOf(listOf(1), listOf(2, 3), listOf(4, 5, 6))
println(deepList.flatten()) // [1, 2, 3, 4, 5, 6]