본문 바로가기
코틀린/[Mapping] 매핑 작업

[Kotlin][Collection] flatMap

by jinwo_o 2024. 8. 6.

원래 배열의 각 요소에 대해 호출된 변환 함수의 결과에서 생성된 모든 요소의 단일 목록을 반환합니다.

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("123", "45")
println(list.flatMap { it.toList() }) // [1, 2, 3, 4, 5]

val list = listOf(1, 2, 3, 4, 5)
val intervals: Array<IntArray> = arrayOf(intArrayOf(1, 3), intArrayOf(0, 4))
print(intervals.flatMap { (left, right) -> list.slice(left..right) }) // [2, 3, 4, 1, 2, 3, 4, 5]

 

flatMap - Kotlin Programming Language

 

kotlinlang.org

 

'코틀린 > [Mapping] 매핑 작업' 카테고리의 다른 글

[Kotlin][String] replace  (0) 2024.08.27
[Kotlin][Collection] zip  (0) 2024.08.22
[Kotlin][Collection] map / mapIndexed  (0) 2024.08.06