To clear all key-value pairs from a map in Kotlin, you can use the clear method. This method removes all elements from the map, leaving it empty.
We can clear all key-value pairs from a map in Kotlin using the clear method, which removes all elements from the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map.size
property to verify that the map is empty.fun main() {
// Declare and initialize a mutable map
val myMap: MutableMap<String, Int> = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Clear all key-value pairs using clear method
myMap.clear()
// Print the size of the map
println("Size of the map after clearing: ${myMap.size}")
}
Size of the map after clearing: 0
We can use the clear method on an already empty map in Kotlin, and it will still leave the map empty.
For example,
myMap
. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map, even though it is already empty.size
property to verify that the map is still empty.fun main() {
// Declare and initialize an empty mutable map
val myMap: MutableMap<String, Int> = mutableMapOf()
// Clear the map using clear method
myMap.clear()
// Print the size of the map
println("Size of the map after clearing: ${myMap.size}")
}
Size of the map after clearing: 0
We can insert key-value pairs into a map and then clear all key-value pairs using the clear method.
For example,
myMap
and inserting some key-value pairs into it. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map.size
property to verify that the map is empty.fun main() {
// Declare and initialize a mutable map
val myMap: MutableMap<String, Int> = mutableMapOf()
myMap["one"] = 1
myMap["two"] = 2
myMap["three"] = 3
// Clear all key-value pairs using clear method
myMap.clear()
// Print the size of the map
println("Size of the map after clearing: ${myMap.size}")
}
Size of the map after clearing: 0
In this tutorial, we learned How to Clear All Key-Value Pairs from a Map in Kotlin language with well detailed examples.