Kotlin List.count() Function

The Kotlin List.count() function finds the number of elements matching the given predicate and returns that value.

Syntax of List.count()

The syntax to call List.count() function is

list.count(predicate)
ParameterDescription
predicateA function which returns a boolean value for a given element.

Return Value

ValueScenario
An integer representing the number of matches for predicateWhen there are matches in the list for given predicate
0When there are no matches in the list.

Example 1: Count Matches in List

In this example, we will take a list of integers, and count the number of even numbers in this list. The predicate is such that, it returns true if the number is even.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(2, 8, 5, 7, 9, 6, 10)
    val predicate: (Int) -> Boolean = {it % 2 == 0}
    val result = list1.count(predicate)
    print("Number of matches in the list: $result")
}

Output

Number of matches in the list: 4

Example 2: Count Matches in List of Strings

In this example, we will take list of strings, and a predicate which returns true if the string length is 2. We will use list.count() and predicate, to count the number of elements in the list with length 2.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("co", "com", "iso", "dev", "io", "in")
    val predicate: (String) -> Boolean = {it.length == 2}
    val result = list1.count(predicate)
    print("Number of matches in the list: $result")
}

Output

Number of matches in the list: 3

Conclusion

In this Kotlin Tutorial, we learned how to count the number of matches for a predicate in the given list, using Kotlin List.count() function.