Kotlin List count()
Syntax & Examples


Syntax of List.count()

The syntax of List.count() extension function is:

fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int

This count() extension function of List returns the number of elements matching the given predicate.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the characters 'a', 'p', 'p', 'l', 'e'.
  • We use the count function with a predicate that checks if each element is equal to 'p'.
  • The result, which is an integer count, is stored in count.
  • Since there are two occurrences of 'p' in list1, the expression list1.count { it == 'p' } returns 2.
  • Finally, we print the value of count to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(&quot;a&quot;, &quot;p&quot;, &quot;p&quot;, &quot;l&quot;, &quot;e&quot;);
    val count = list1.count { it == "p" };
    print(count);
}

Output

2

2 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30.
  • We use the count function with a predicate that checks if each element is greater than 15.
  • The result, which is an integer count, is stored in count.
  • Since there are two elements greater than 15 in list1, the expression list1.count { it > 15 } returns 2.
  • Finally, we print the value of count to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val count = list1.count { it > 15 };
    print(count);
}

Output

2

3 Example

In this example,

  • We create a list named list1 containing the strings 'apple', 'banana', 'mango', 'orange'.
  • We use the count function with a predicate that checks if each element starts with the letter 'a'.
  • The result, which is an integer count, is stored in count.
  • Since there are two strings in list1 starting with 'a', the expression list1.count { it.startsWith('a') } returns 2.
  • Finally, we print the value of count to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;mango&quot;, &quot;orange&quot;);
    val count = list1.count { it.startsWith('a') };
    print(count);
}

Output

1

Summary

In this Kotlin tutorial, we learned about count() extension function of List: the syntax and few working examples with output and detailed explanation for each example.