To count the number of occurrences of a specified element in an array in Kotlin, you can use the count
method of the Array class.
In this example,
arr
with integer values.count
method of the array object arr
with a lambda expression to count the occurrences of a specific integer.count
method returns the number of elements that match the condition.fun main(args: Array<String>) {
val arr = arrayOf(1, 2, 3, 2, 4, 2, 5)
val count = arr.count { it == 2 }
println("Number of occurrences of element 2: $count")
}
Number of occurrences of element 2: 3
In this example,
arr
with string values.count
method of the array object arr
with a lambda expression to count the occurrences of a specific string.count
method returns the number of elements that match the condition.fun main(args: Array<String>) {
val arr = arrayOf("apple", "banana", "cherry", "apple", "date", "apple")
val count = arr.count { it == "apple" }
println("Number of occurrences of element 'apple': $count")
}
Number of occurrences of element 'apple': 3
In this tutorial, we learned How to count the Number of Occurrences of Specified Element in the Array in Kotlin language with well detailed examples.