본문 바로가기
코틀린/[Filtering] 필터 작업

[Kotlin][Collection] partition

by jinwo_o 2024. 8. 21.

원래 배열을 목록 쌍으로 분할합니다. 여기서 첫 번째 목록에는 조건자가 true 를 생성한 요소가 포함되고, 두 번째 목록에는 조건자가 false 를 생성한 요소가 포함됩니다.

public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
    val first = ArrayList<T>()
    val second = ArrayList<T>()
    for (element in this) {
        if (predicate(element)) {
            first.add(element)
        } else {
            second.add(element)
        }
    }
    return Pair(first, second)
}


val array = intArrayOf(1, 2, 3, 4, 5)
val (even, odd) = array.partition { it % 2 == 0 }
println(even) // [2, 4]
println(odd) // [1, 3, 5]

 

partition - Kotlin Programming Language

 

kotlinlang.org