Kotlin Array - count() Function



The Kotlin array count() function retrieves the number of elements matching the given predicate.

This function has 2 implementations which are the overloaded versions of the function. One of the functions doesnt accept any input parameters that directly return the number of elements in the array. The other overloaded count() function accepts a Boolean predicate function and only returns the number of elements in the array that matched with given predicate.

Syntax

Following is the syntax of Kotlin array count() function −

fun <T> Array<out T>.count(): Int
or,
inline fun <T> Array<out T>.count(
    predicate: (T) -> Boolean
): Int

Parameters

The first overloaded function does not accepts parameters, Other one accepts a single parameters. i.e. predicate, represent the condition.

Return value

This function returns an integer value that is the number of the element.

Example 1

Following is the basic example returns the number of element without any predicate −

fun main(args: Array<String>) {
   var array = Array(10) { i -> i}
   var result = array.count()
   println("The number of elements in the array is $result")
}

Output

Following is the output −

The number of elements in the array is 10

Example 2

Now, let's consider another example. Here, we create an array to store elements and count the number of elements according to the predicate −

fun main(args: Array<String>) {
   var array = Array(10) { i ->
      if(i<3) {'c'}
      else if(i<5) {"Hi"}
      else {5}
   }
   var result = array.count { i -> i is Int }
   println("The number of elements in the array which are of type integer is $result")
}

Output

Following is the output −

The number of elements in the array which are of type integer is 5

Example 3

The example below creates an array with random values. Then, we use the count() function to display the number of elements in the array that are equal to 10 −

fun main(args: Array<String>) {
   var array = arrayOf(10, 23.4, 'c', "Hi", 10)
   var result = array.count { i -> i==10 }
   println("The number of elements in the array which are equal to 10 is $result")
}

Output

Following is the output −

The number of elements in the array which are equal to 10 is 2
kotlin_arrays.htm
Advertisements