Kotlin List.count() – Examples

Kotlin List.count()

The Kotlin List.count() function returns an integer that represents the number of elements matching the given predicate.

Syntax

List.count(predicate)

Example 1

In this example,

  1. Take a list of integers.
  2. Define a predicate that returns true for an even number.
  3. Call count() function on the list, with predicate passed as argument to the function. The function should return the number of matches.

Program

fun main(args: Array<String>) {
    val list1 = listOf(24, 6, 44, 10, 3, 8, 9)
    val predicate: (Int) -> Boolean = {it % 2 == 0}
    val result = list1.count(predicate)
    print(result)
}

Output

5

There are five even numbers, hence the return value of 5.

Example 2

In this example,

  1. Take a list of string.
  2. Define a predicate that returns true for an input string of length 3.
  3. Call count() function on the list, with predicate passed as argument to the function. The function should return the number of matches.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "abc", "abcd", "cde")
    val predicate: (String) -> Boolean = {it.length == 3}
    val result = list1.count(predicate)
    print(result)
}

Output

2