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

[Kotlin][Collection] map / mapIndexed

by jinwo_o 2024. 8. 6.

주어진 변환 함수를 원본 배열의 각 요소에 적용한 결과가 포함된 배열을 반환합니다.

public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
    return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}

public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) -> R): C {
    for (item in this)
        destination.add(transform(item))
    return destination
}


val numbers = listOf(1, 2, 3)
println(numbers.map { it * it }) // [1, 4, 9]

"123456789".map { char -> 
    print(char) // 아스키코드 값
    print(char.digitToInt()) // Int
}

 

주어진 변환 함수를 각 요소에 적용한 결과와 원본 배열의 해당 인덱스를 포함하는 목록을 반환합니다.

public inline fun <T, R> Iterable<T>.mapIndexed(transform: (index: Int, T) -> R): List<R> {
    return mapIndexedTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}

public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo(destination: C, transform: (index: Int, T) -> R): C {
    var index = 0
    for (item in this)
        destination.add(transform(checkIndexOverflow(index++), item))
    return destination
}


val list = IntArray(5) { it }
val mappedList: List<Pair<Int, Int>> = list.mapIndexed { i, v -> i to v }
mappedList.forEach { print("${it.first}, ${it.second}")

 

map - Kotlin Programming Language

 

kotlinlang.org

 

mapIndexed - Kotlin Programming Language

 

kotlinlang.org

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

[Kotlin][String] replace  (0) 2024.08.27
[Kotlin][Collection] zip  (0) 2024.08.22
[Kotlin][Collection] flatMap  (0) 2024.08.06