Kotlin Array count()
In Kotlin, the count()
function is used to determine the number of elements in an array that satisfy a given condition. It returns the count as an integer.
This function is useful when you need to find out how many elements in an array meet a specific criterion.
In this tutorial, we’ll explore the syntax of the count()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the count()
function is as follows:
fun <T> Array<out T>.count(): Int
fun <T> Array<out T>.count(predicate: (T) -> Boolean): Int
where
Parameter | Description |
---|---|
predicate | [Optional] A function that defines the condition. |
If predicate
is not specified as argument, then the count() function returns the number of elements in the array.
Examples for Array count() function
1. Using count() to Count Even Numbers
In this example, we’ll use count()
to determine the number of even numbers in an array of integers numbersArray
.
Kotlin Program
fun main() {
val numbersArray = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// Using count() to count even numbers
val countEvenNumbers = numbersArray.count { it % 2 == 0 }
// Printing the original array and the result
println("Numbers: ${numbersArray.joinToString(", ")}")
println("Count of Even Numbers: $countEvenNumbers")
}
Output
Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Count of Even Numbers: 5
2. Using count() to Count Words Starting with ‘A’
In this example, we’ll use count()
to find out how many words in an array start with the letter ‘A’.
Kotlin Program
fun main() {
val wordsArray = arrayOf("apple", "banana", "orange", "avocado", "kiwi")
// Using count() to count words starting with 'A'
val countWordsStartingWithA = wordsArray.count { it.startsWith('a') }
// Printing the original array and the result
println("Words: ${wordsArray.joinToString(", ")}")
println("Count of Words Starting with 'a': $countWordsStartingWithA")
}
Output
Words: apple, banana, orange, avocado, kiwi
Count of Words Starting with 'a': 2
3. Using count() to count number of elements in Array
In this example, we’ll use count()
to find the number of elements in an array.
Kotlin Program
fun main() {
val wordsArray = arrayOf("apple", "banana", "orange", "avocado", "kiwi")
val arrayLength = wordsArray.count()
println("Array Length : $arrayLength")
}
Output
Array Length : 5
Summary
In this tutorial, we’ve covered the count()
function in Kotlin arrays, its syntax, and how to use it to determine the number of elements that satisfy a given condition.