Count items in a List matching a predicate in Kotlin
This article explores different ways to count items in a list matching a predicate in Kotlin.
1. Using size property
The standard solution to find the number of elements in a list in Kotlin is calling its size property.
|
1 2 3 4 5 |
fun main() { val l = (0.. 100).toList() val count = l.size println(count) // 100 } |
To count only items that match a predicate, use the filter() method:
|
1 2 3 4 5 6 7 8 |
data class Product(val name: String, val price: Int) fun main() { val items = listOf(Product("1", 10), Product("2", 20), Product("3", 30)) val count = items.filter { it.price > 10 }.size println(count) // 2 } |
2. Using count() function
Another possibility is using the count() function, which returns the count of elements in the list.
|
1 2 3 4 5 |
fun main() { val l = (0.. 100).toList() val count = l.count() println(count) // 100 } |
To count the number of elements matching a predicate, you can do like below:
|
1 2 3 4 5 6 7 8 |
data class Product(val name: String, val price: Int) fun main() { val items = listOf(Product("1", 10), Product("2", 20), Product("3", 30)) val count = items.count { it.price > 10 } println(count) // 2 } |
That’s all about counting items in a list matching a predicate in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)