flatMap
flatMap
transforms each element of a collection into an iterable object and builds a single list of the transformation results. The transformation is user-defined.
fun main() {
val fruitsBag = listOf("apple","orange","banana","grapes") // 1
val clothesBag = listOf("shirts","pants","jeans") // 2
val cart = listOf(fruitsBag, clothesBag) // 3
val mapBag = cart.map { it } // 4
val flatMapBag = cart.flatMap { it } // 5
println("Your bags are: $mapBag")
println("The things you bought are: $flatMapBag")
}
- Defines a collection of Strings with fruit names.
- Defines a collection of Strings with clothes names.
- Adds
fruitsBag
andclothesBag
to thecart
list. - Builds a
map
ofcart
elements, which is a list of two lists. - Builds a
flatMap
ofcart
elements, which is a single list consisting of elements from both lists.