To count the number of occurrences of a specific element in a list in Kotlin, you can use the count
method along with a lambda expression to specify the element to count.
In this example,
numbers
containing integer elements.count
method with a lambda expression that checks for the desired element.count
method tallies the occurrences.fun main() {
val numbers = listOf(1, 2, 3, 4, 1, 2, 1)
val count = numbers.count { it == 1 }
println("Count of 1 is: $count")
}
Count of 1 is: 3
In this example,
words
containing string elements.count
method with a lambda expression to check for the desired string.count
method tallies the occurrences.fun main() {
val words = listOf("apple", "banana", "apple", "cherry")
val count = words.count { it == "apple" }
println("Count of 'apple' is: $count")
}
Count of 'apple' is: 2
In this tutorial, we learned How to count the Number of Occurrences of Specific Element in the List in Kotlin language with well detailed examples.