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(): BooleanThis 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
map1containing key-value pairs. - We use the
isNotEmpty()function to check ifmap1is not empty. - As
map1contains elements,trueis 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 ifmap2is not empty. - As
map2does not contain any elements,falseis 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
map3containing key-value pairs. - We use the
isNotEmpty()function to check ifmap3is not empty. - As
map3contains elements,trueis 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.