Flat family
Say you have a list of other lists. You probably got it from different database queries, or maybe from different configuration files:
val listOfLists = listOf(listOf(1, 2), listOf(3, 4, 5), listOf(6, 7, 8)) // [[1, 2], [3, 4, 5], [6, 7, 8]]
And you want to turn them into a single list such as the following:
[1, 2, 3, 4, 5, 6, 7, 8]
One way to merge those lists is to write some imperative code:
val results = mutableListOf<Int>() for (l in listOfLists) { results.addAll(l) }
But calling flatten()
will do the same for you:
listOfLists.flatten()
You can also control what happens with those results using flatMap()
:
println(listOfLists.flatMap { it.asReversed() })
Note that in this case, it refers to one of the sublists.
You can also decide to use flatMap()
for type conversions:
println(listOfLists.flatMap { it.map { it.toDouble() } // ^ ^ // (1) (2) })
The preceding code prints the following output:
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
We converted all integers...