The count() extension function for sets in Kotlin returns the number of elements in the set that match the given predicate.
The syntax of Set.count() extension function is:
fun <T> Set<T>.count(predicate: (T) -> Boolean): Int
This count() extension function of Set returns the number of elements matching the given predicate.
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes an element of the set and returns a Boolean indicating whether the element matches the condition. |
Set.count() returns value of type Int
.
In Kotlin, we can use the count()
function to count the number of even elements in a set of integers.
For example,
count()
function with a predicate that checks if an element is even.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5, 6)
val evenCount = numbers.count { it % 2 == 0 }
println("Number of even elements: $evenCount")
}
Number of even elements: 3
In Kotlin, we can use the count()
function to count the number of strings in a set that have a length greater than 5.
For example,
count()
function with a predicate that checks if the length of the string is greater than 5.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry", "date")
val longFruitsCount = fruits.count { it.length > 5 }
println("Number of fruits with length greater than 5: $longFruitsCount")
}
Number of fruits with length greater than 5: 2
In Kotlin, we can use the count()
function to count elements in an empty set that match a given predicate, which will always return 0.
For example,
count()
function with a predicate that checks if an element is positive.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val positiveCount = emptySet.count { it > 0 }
println("Number of positive elements in empty set: $positiveCount")
}
Number of positive elements in empty set: 0
In this Kotlin tutorial, we learned about count() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.