원래 배열을 목록 쌍으로 분할합니다. 여기서 첫 번째 목록에는 조건자가 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
'코틀린 > [Filtering] 필터 작업' 카테고리의 다른 글
[Kotlin][Collection] takeWhile / takeLastWhile (0) | 2024.08.28 |
---|---|
[Kotlin][Collection] filter / filterNot / filterIndexed (0) | 2024.08.16 |
[Kotlin][Collection] all / any / none (0) | 2024.08.08 |