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 typeInt
and values of typeString
. - We then use the
isEmpty()
function to check ifmap1
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 typeChar
and values of typeInt
, containing three key-value pairs. - We then use the
isEmpty()
function to check ifmap2
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 typeString
and values of typeInt
. - We then use the
isEmpty()
function to check ifmap3
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.