Kotlin Tutorials

Kotlin Map isEmpty()
Syntax & Examples

Syntax of Map.isEmpty()

The syntax of Map.isEmpty() function is:

abstract fun isEmpty(): Boolean

This isEmpty() function of Map returns true if the map is empty (contains no elements), false otherwise.



✐ Examples

1 Check if an empty map is empty

In this example,

  • We create an empty map named map1 with keys of type Int and values of type String.
  • We then use the isEmpty() function to check if map1 is empty, which it is.
  • The result, which is true, is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = emptyMap<Int, String>()
    val result = map1.isEmpty()
    println(result)
}

Output

true

2 Check if a non-empty map is empty

In this example,

  • We create a map named map2 with keys of type Char and values of type Int, containing three key-value pairs.
  • We then use the isEmpty() function to check if map2 is empty, which it is not.
  • The result, which is false, is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
    val result = map2.isEmpty()
    println(result)
}

Output

false

3 Check if another empty map is empty

In this example,

  • We create another empty map named map3 with keys of type String and values of type Int.
  • We then use the isEmpty() function to check if map3 is empty, which it is.
  • The result, which is true, is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = emptyMap<String, Int>()
    val result = map3.isEmpty()
    println(result)
}

Output

true

Summary

In this Kotlin tutorial, we learned about isEmpty() function of Map: the syntax and few working examples with output and detailed explanation for each example.