Kotlin Map - isEmpty() Function



The Kotlin Map isEmpty() function is used to return the boolean value. True if the map is empty means the map does not contain any element. False if the map contains the element.

There are the following use cases of the isEmpty() function:

  • Validation: Before proceeding with a map, make sure it contains elements to avoid errors or unnecessary operations.
  • Conditional Logic: This function executes different code paths depending on whether the map is empty or not.
The isEmpty() function enhances readability, reduces boilerplate code, and improves code safety in various scenarios.

Syntax

Following is the syntax of Kotlin map isEmpty() function −

Map.isEmpty()

Parameters

This function does not accepts any parameters.

Return value

This function returns true if the map does not contains any element otherwise returns false.

Example 1: Checking if a Map is Empty or NOt

Let's see a basic example of the isEmpty() function, which returns true if the map is empty.

fun main(args: Array<String>) {
   val emptyMap = mapOf<Int, String>()
   if (emptyMap.isEmpty()) {
      println("The map is empty.")
   } else {
      println("The map contains: $emptyMap")
   }
}

Output

Following is the output −

The map is empty.

Example 2: Map is not Empty

The following example uses the isEmpty() function and returns the false statement if the map is not empty −

fun main(args: Array<String>) {
   // Map is not empty
   val populatedMap = mapOf(1 to "Apple", 2 to "Banana", 3 to "Orange")
   if (populatedMap.isEmpty()) {
      println("The map is empty.")
   } else {
      println("The map contains: $populatedMap")
   }
}

Output

Following is the output −

Not enough tasks to proceed.

Example 3: Avoiding Null Pointer Exceptions

The below example checks whether the productStock map is empty or not and print a message accordingly −

fun main(args: Array<String>) {
   val productStock: Map<String, Int> = mapOf()

   if (!productStock.isEmpty()) {
      println("First product: ${productStock.keys.first()}")
   } else {
      println("No products in stock.")
   }
}

Output

Following is the output −

No products in stock.
kotlin_maps.htm
Advertisements