Kotlin Tutorials

Kotlin Map isNotEmpty()
Syntax & Examples

Syntax of Map.isNotEmpty()

The syntax of Map.isNotEmpty() extension function is:

fun <K, V> Map<out K, V>.isNotEmpty(): Boolean

This isNotEmpty() extension function of Map returns true if this map is not empty.



✐ Examples

1 Non-empty map

In this example,

  • We create a map named map1 containing key-value pairs.
  • We use the isNotEmpty() function to check if map1 is not empty.
  • As map1 contains elements, true is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf("a" to 1, "b" to 2, "c" to 3)
    println(map1.isNotEmpty())
}

Output

true

2 Empty map

In this example,

  • We create an empty map named map2.
  • We use the isNotEmpty() function to check if map2 is not empty.
  • As map2 does not contain any elements, false is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf<Int, Char>()
    println(map2.isNotEmpty())
}

Output

false

3 Non-empty map

In this example,

  • We create a map named map3 containing key-value pairs.
  • We use the isNotEmpty() function to check if map3 is not empty.
  • As map3 contains elements, true is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry")
    println(map3.isNotEmpty())
}

Output

true

Summary

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