Blog / October 23, 2019 / 2 mins read / By Suneet Agrawal

partition() : Kotlin

The collection is something which is used by almost everyone. It makes our life easy. List, Set and Map are the best examples of them. Even the programming language in which you are writing code provides you with a few basic operations that can be performed on those collections, But sometimes you need even more operations.

Recently in one of my use case, the basic operations were not enough for me. My use case was very simple. I was having a list on which I need to perform an operation to segregate its items into two lists, one which agrees to some condition and the other which doesn’t.

The typical way to do this is to run a loop over the collection object and add an if condition inside and segregate the object.

val list = listOf(1 , 2, 3, 4, 5)

val evenList = mutableListOf<Int>()
val oddList = mutableListOf<Int>()

for(item in list){
    if(item % 2 == 0){
        evenList.add(item)
    } else {
        oddList.add(item)
    }
}
 
println(evenList)
println(oddList)

Kotlin has something inbuild, which can make your life easier. There is an operator caller partition() which can segregate the list into two lists, one with the items matching the condition and another one with the non-matching condition.

val list = listOf(1 , 2, 3, 4, 5)
val (even, odd) = list.partition { it % 2 == 0}
   
println(even)
println(odd)

If you check the actual implementation of the partition function, this is actually the same.

/**
 * Splits the original collection into pair of lists,
 * where *first* list contains elements for which [predicate] yielded `true`,
 * while *second* list contains elements for which [predicate] yielded `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)
}

There is no difference in the implementation but since its an inbuild inline function, you don’t have to write the entire iteration and condition check on your own. Please note that there is no difference in time or space complexity also.

The only reason I wrote about this as a blog is because I feel I am lazy and prefers to use all inbuild functions to write fewer lines of code. :) This was one of them.

Comments