Kotlin Count Function
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.
To iterate, filter or modify the existing collection object, Kotlin provides us with a few in builds functions. Count function is one of them.
Lets try to understand the count function in detail.
This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-count-function/ and later reposted on Medium.
What is Count function?
The count function is used to get the total number of elements in the collection.
It can also be used to get the number of elements in the collection that satisfy some condition.
The count function has two overloads.
First one takes zero arguments and returns the total elements in the collection.
Other one takes a higher order function (predicate) as an argument and returns the number of elements in the collection which confirms that predicate.
/**
* Returns the number of elements in this collection.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.count(): Int {
return size
}
/**
* Returns the number of elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int {
if (this is Collection && isEmpty()) return 0
var count = 0
for (element in this) if (predicate(element)) checkCountOverflow(++count)
return count
}
The first overload of count function doesn’t take any parameter and it returns the size of the collection. It actually returns the size variable.
The second overload take a predicate and returns the count of the elements which satisfy that predicate. The predicate takes every element one by one as a parameter and return a bool type.
Both the overloads of count are available in all type of arrays like IntArray, CharArray and many more. They are also available in collection means in List, Set and Map.
All the above implements are extension functions which returns the count of elements in that collection conditionally or unconditionally.
Filter with List
count function can be used over a list to get the size of the list. It can also be used to get the count of elements in the list that confirms the condition. The second overload can be used with a named parameter or using it.
The code will look like below.
val list = listOf(1, 2, 3, 4, 5)
println(list.count())
println(list.count { it % 2 == 0 })
println(list.count { item -> item % 2 == 0 })
Filter with Set
Similar to list, count function can be used over a set to get the size of the set. It can also be used to get the count of elements in the set that confirms the condition. The second overload can be used with a named parameter or using it.