Kotlin Collection

[Kotlin] partition

별볼일있는 개발자 2024. 9. 7. 15:07

partition 공식문서

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/partition.html

 

partition이란

컬렉션을 특정 조건을 만족하는 그룹과 그렇지 않은 그룹으로 두 개의 리스트로 나눠야 할 때 사용합니다.

filter, filterNot을 따로 사용할 필요 없이 한 번의 연산으로 두 개의 리스트를 반환합니다.

 

1) filter, filterNot 을 활용한 예시

class Person(val name: String, val age: Int) {
    override fun toString(): String {
        return "Person(name='$name', age=$age)"
    }
}

fun main(){
	val people = listOf(
    	Person("Grant", 30),
        Person("John", 25),
        Person("Obama", 40)
    )
    
    val youngPeople = people.filter { it.age < 30}
    val oldPeople = people.filterNot { it.age < 30}
    
    println(youngPeople) // [Person(name='John', age=25)]
    println(oldPeople)  // [Person(name='Grant', age=30), Person(name='Obama', age=40)]
}

 

이런식으로 filter, filterNot 을 활용해서 두 개의 리스트로 나눌 수도 있습니다.

하지만 partition 을 쓰면 좀 더 간략하게 코드를 작성할 수 있습니다.

 

2) partition 을 활용한 간결한 코드

class Person(val name: String, val age: Int) {
    override fun toString(): String {
        return "Person(name='$name', age=$age)"
    }
}

fun main() {
    val people = listOf(
    	Person("Grant", 30),
        Person("John", 25),
        Person("Obama", 40)
    )
    
    val (youngPeople, oldPeople) = people.partition { it.age < 30}
    
    println(youngPeople) // [Person(name='John', age=25)]
    println(oldPeople)  // [Person(name='Grant', age=30), Person(name='Obama', age=40)]
}

 

구조 분해 선언을 활용하여 반환된 Pair 값을 개별 변수로 직접 받을 수도 있습니다. youngPeople 에는 조건에 만족하는 리스트가, oldPeople 에는 조건에 만족하지 않는 리스트가 반환됩니다.

(첫번째 리스트에는 조건에 만족하는 리스트가, 두번째 리스트에는 조건에 만족하지 않는 리스트가 담긴다고 생각하면 됩니다)

 

 

 

partition의 내부 구조

partition의 내부 구현을 보면 두 개의 ArrayList를 생성하고, 조건에 맞게 값을 추가한 후 Pair(first, second)를 반환하는 것을 알 수 있습니다.

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)
}

 

partition은 내부적으로 filter & filterNot을 동시에 수행하므로 한 번의 순회만 필요하여 성능적으로 효율적입니다. 컬렉션을 특정 조건에 따라 2개의 리스트로 분리를 해야하는 경우에 사용하면 됩니다.

'Kotlin Collection' 카테고리의 다른 글

[Kotlin] sortedWith()  (2) 2024.09.10
[Kotlin] joinToString  (0) 2024.09.06