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'
inlist1
, the expressionlist1.count { it == 'p' }
returns2
. - Finally, we print the value of
count
to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "p", "p", "l", "e");
val count = list1.count { it == "p" };
print(count);
}
Output
2
2 Example
In this example,
- We create a list named
list1
containing the integers10, 20, 30
. - We use the
count
function with a predicate that checks if each element is greater than15
. - The result, which is an integer count, is stored in
count
. - Since there are two elements greater than
15
inlist1
, the expressionlist1.count { it > 15 }
returns2
. - 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 expressionlist1.count { it.startsWith('a') }
returns2
. - Finally, we print the value of
count
to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "mango", "orange");
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.