Hi, I am Amit Shekhar, Co-Founder @ Outcome School • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.
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.
This article was originally published at Outcome School.
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
yieldstrue
. - The second list contains elements for which the
predicate
yieldsfalse
.
That's it for now.
Thanks
Amit Shekhar
Co-Founder @ Outcome School
You can connect with me on:
Top comments (0)