0
0
Kotlinprogramming~5 mins

Collection size and emptiness checks in Kotlin

Choose your learning style9 modes available
Introduction
We check if a collection has items or is empty to decide what to do next in our program.
When you want to see if a list has any elements before processing it.
Before showing data from a collection, check if it is empty to show a message instead.
To avoid errors by making sure a collection is not empty before accessing its items.
When you want to count how many items are in a collection to display or use that number.
Syntax
Kotlin
collection.isEmpty()
collection.isNotEmpty()
collection.size
collection.count()
Use isEmpty() to check if the collection has no elements.
Use isNotEmpty() to check if the collection has one or more elements.
Examples
Check if the list has elements or not.
Kotlin
val list = listOf(1, 2, 3)
println(list.isEmpty())  // false
println(list.isNotEmpty())  // true
Check an empty list returns true for isEmpty.
Kotlin
val emptyList = emptyList<String>()
println(emptyList.isEmpty())  // true
println(emptyList.isNotEmpty())  // false
Get the number of items in the list using size or count.
Kotlin
val fruits = listOf("apple", "banana", "cherry")
println(fruits.size)  // 3
println(fruits.count())  // 3
Sample Program
This program checks if the list 'numbers' has items and prints the count or a message if empty.
Kotlin
fun main() {
    val numbers = listOf(10, 20, 30)
    if (numbers.isNotEmpty()) {
        println("The list has ${numbers.size} items.")
    } else {
        println("The list is empty.")
    }
}
OutputSuccess
Important Notes
Using isEmpty() and isNotEmpty() is clearer and safer than comparing size to zero.
Both size and count() return the number of elements; size is usually faster.
Checking emptiness helps avoid errors when accessing elements in a collection.
Summary
Use isEmpty() to check if a collection has no elements.
Use isNotEmpty() to check if it has one or more elements.
Use size or count() to find how many items are in the collection.