> For the complete documentation index, see [llms.txt](https://gold.gitbook.io/kotlin/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gold.gitbook.io/kotlin/collections/mapping-operations/flatmap.md).

# flatMap

monad. 이름에서 처럼 flat 하게 변형시킨다. T 를 받아 Iterable\<R>을 리턴한다면 이중리스트가 되겠지만 flatMap 은 그걸 flatten 해서 단일 리스트를 반환한다

```kotlin
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

public inline fun <T, R, C : MutableCollection<in R>>
Iterable<T>.flatMapTo(destination: C, transform: (T) -> Iterable<R>): C {
    for (element in this) {
        val list = transform(element)
        destination.addAll(list)
    }
    return destination
}


val list = listOf(1, 2, 3, 4, 5)
println(list.flatMap{ listOf(it, it * 2, it * 3) })
// [1, 2, 3, 2, 4, 6, 3, 6, 9, 4, 8, 12, 5, 10, 15]
```
