Kotlin Set count Example

This post shows the usage of Kotlin count() method with an example. The count() method returns the number of elements in the set.

Kotlin Set count Example

The example returns the number of values in the set, the number of negative values and the number of even values.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = setOf(12, 1,2,5,4,2)

    val len = nums.count()
    println("There are $len elements")
    
    val size = nums.size
    println("The size of the list is $size")    

    val n1 = nums.count { e -> e < 0 }
    println("There are $n1 negative values")

    val n2 = nums.count { e -> e % 2 == 0 }
    println("There are $n2 even values")
}
Output:
There are 5 elements
The size of the list is 5
There are 0 negative values
There are 3 even values


Comments