How to flatten List of Lists in Kotlin?

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.


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]