partition - filtering function in Kotlin

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
partition - filtering function in Kotlin

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about the Kotlin filtering function - partition. It filters a collection by a predicate and keeps the elements that don't match it in a separate list.

There are many useful collection functions in Kotlin. It is good to know about those and use those based on the requirement. One of those collection functions is partition.

partition filters a collection by a predicate and keeps the elements that don't match it in a separate list.

Let's learn by example.

Consider a data class User like below:

data class User(val id: Int, val name: String, val isMentor: Boolean)

And, a list of User:

val users = arrayOf(
    User(1, "Amit", true),
    User(2, "Ronaldo", false),
    User(1, "Messi", true),
    User(3, "Neymar", false))

Now, let's use the partition function on this list of users to filter the users who are a mentor and the users who are not a mentor.

val (mentors, notMentors) = users.partition { it.isMentor }

Now, let's print mentors

println(mentors)

This will print the following:

[User(id=1, name=Amit, isMentor=true),
User(id=1, name=Messi, isMentor=true)]

And, when we print notMentors

println(notMentors)

This will print the following:

[User(id=2, name=Ronaldo, isMentor=false),
User(id=3, name=Neymar, isMentor=false)]

If we go through the source code, we will find the following implementation:

public inline fun <T> Array<out 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)
}

It is doing the same thing that we would have also done. It is just that Kotlin provides these useful functions out of the box so that we can use them directly.

Note:

  • It takes a predicate.
  • It splits the original array into pair of lists and returns Pair<List<T>, List<T>>.
  • The first list contains elements for which the predicate yields true.
  • The second list contains elements for which the predicate yields false.

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.