How to partition a list in Kotlin

Partition a list in kotlin :

Partitioning or dividing a list or any other collection is easy in Kotlin. Kotlin provides one inbuilt method that makes it easier for us. In this post, I will show you how to do partition using and without using the provided function.

Method 1: Using a loop :

Our problem is to divide one list of positive and negative numbers in two lists : one list will hold only the positive numbers and the other list hold the negative numbers.

With this method, we will use one loop to iterate the list elements one by one. This loop will check if the current iterating element is positive or negative and based on that it will add that item to different lists :

fun main() {
    val givenList = mutableListOf(1, 2, 3, 4, 5, 6, 7, -8, -9, -10, -11, 12, 13, 14)
    val positiveList = mutableListOf<int>()
    val negativeList = mutableListOf<int>()
    givenList.forEach {
        if (it > 0) positiveList.add(it) else negativeList.add(it)
    }
    println(positiveList)
    println(negativeList)
}

It will print :

[1, 2, 3, 4, 5, 6, 7, 12, 13, 14]
[-8, -9, -10, -11]

Method 2: Using partition(predicate):

Kotlin also provides one inbuilt method to do that : partition. It takes one predicate and returns two lists based on it. The first list contains elements for which the predicate returns true and the second list contains elements for which the predicate returns false.

It looks as like below if we rewrite the above program :

fun main() {
    val givenList = mutableListOf(1, 2, 3, 4, 5, 6, 7, -8, -9, -10, -11, 12, 13, 14)

    val (positiveList, negativeList) = givenList.partition { it > 0 }

    println(positiveList)
    println(negativeList)
}

It will print :

[1, 2, 3, 4, 5, 6, 7, 12, 13, 14]
[-8, -9, -10, -11]

Similar tutorials :