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

[Kotlin][Collection] zip

by jinwo_o 2024. 8. 22.

이 배열과 동일한 인덱스를 가진 다른 배열의 요소로 구성된 쌍 목록을 반환합니다. 반환된 목록에는 가장 짧은 컬렉션의 길이가 있습니다.

public inline fun <T, R, V> Iterable<T>.zip(other: Iterable<R>, transform: (a: T, b: R) -> V): List<V> {
    val first = iterator()
    val second = other.iterator()
    val list = ArrayList<V>(minOf(collectionSizeOrDefault(10), other.collectionSizeOrDefault(10)))
    while (first.hasNext() && second.hasNext()) {
        list.add(transform(first.next(), second.next()))
    }
    return list
}


val listA = listOf("a", "b", "c")
val listB = listOf(1, 2, 3, 4)
val result = listA.zip(listB) { a, b -> "$a$b" }
println(result) // [a1, b2, c3]

 

zip - Kotlin Programming Language

 

kotlinlang.org

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

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