Kotlin Set count()
Syntax & Examples


Set.count() extension function

The count() extension function for sets in Kotlin returns the number of elements in the set that match the given predicate.


Syntax of Set.count()

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.

Parameters

ParameterOptional/RequiredDescription
predicaterequiredA function that takes an element of the set and returns a Boolean indicating whether the element matches the condition.

Return Type

Set.count() returns value of type Int.



✐ Examples

1 Using count() to count even numbers in a set

In Kotlin, we can use the count() function to count the number of even elements in a set of integers.

For example,

  1. Create a set of integers.
  2. Use the count() function with a predicate that checks if an element is even.
  3. Print the result to the console using the println function.

Kotlin Program

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")
}

Output

Number of even elements: 3

2 Using count() to count strings with length greater than 5

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,

  1. Create a set of strings.
  2. Use the count() function with a predicate that checks if the length of the string is greater than 5.
  3. Print the result to the console using the println function.

Kotlin Program

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")
}

Output

Number of fruits with length greater than 5: 2

3 Using count() with an empty set

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,

  1. Create an empty set of integers.
  2. Use the count() function with a predicate that checks if an element is positive.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val positiveCount = emptySet.count { it > 0 }
    println("Number of positive elements in empty set: $positiveCount")
}

Output

Number of positive elements in empty set: 0

Summary

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.