Check if a List is empty in Kotlin
This article explores different ways to check if a List is empty in Kotlin.
1. Using isEmpty() function
The standard solution to check if a list is empty in Kotlin is with the isEmpty() library function. It returns true if the list contains no elements, false otherwise. Following is a simple example demonstrating the usage of this method, which handles null input gracefully.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun isEmpty(list: List<*>?): Boolean { return list == null || list.isEmpty() } fun main() { val list = listOf<Int>() val isEmpty = isEmpty(list) if (isEmpty) { println("The list is empty") } else { println("The list is not empty") } } |
Output:
The list is empty
2. Using isNotEmpty() function
Alternatively, we can check if the list is not empty using the isNotEmpty() function. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun isNotEmpty(list: List<*>?): Boolean { return list != null && list.isNotEmpty() } fun main() { val list = listOf<Int>() val isNotEmpty = isNotEmpty(list) if (isNotEmpty) { println("The list is not empty") } else { println("The list is empty") } } |
Output:
The list is empty
3. Checking List of Lists
To check for an empty list or a null value in a List of Lists, we can use the any() function that returns true if at least one element matches the given predicate.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun isAnyEmpty(listOfLists: List<List<Int>?>): Boolean { return listOfLists.any { it == null || it.isEmpty() } } fun main() { val listOfLists = listOf(listOf(1, 2, 3), null, listOf(4, 5)) val isAnyEmpty = isAnyEmpty(listOfLists) if (isAnyEmpty) { println("The list contains a null or an empty list") } } |
Output:
The list contains a null or an empty list
That’s all about checking if a List is empty 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 :)