How to clear all elements from a HashMap in Kotlin
How to clear all elements from a HashMap in Kotlin.
Here's a step-by-step tutorial on how to clear all elements from a HashMap in Kotlin.
Step 1: Create a HashMap
First, we need to create a HashMap in Kotlin. A HashMap is a collection that stores key-value pairs. Here's an example of how to create a HashMap:
val hashMap = HashMap<Int, String>()
hashMap[1] = "Apple"
hashMap[2] = "Banana"
hashMap[3] = "Cherry"
In this example, we created a HashMap with keys of type Int and values of type String. We added three key-value pairs to the HashMap.
Step 2: Clear the HashMap
To clear all elements from a HashMap, we can use the clear() method. This method removes all key-value pairs from the HashMap. Here's how to use it:
hashMap.clear()
After executing this line of code, the HashMap will be empty, and all key-value pairs will be removed.
Step 3: Verify the HashMap is Empty
To verify that all elements have been cleared from the HashMap, we can check its size. If the size is 0, it means the HashMap is empty. Here's how to check the size of the HashMap:
if (hashMap.isEmpty()) {
println("HashMap is empty")
} else {
println("HashMap is not empty")
}
If the HashMap is empty, the output will be "HashMap is empty". If the HashMap is not empty, the output will be "HashMap is not empty".
Example
Here's an example that puts all the steps together:
fun main() {
val hashMap = HashMap<Int, String>()
hashMap[1] = "Apple"
hashMap[2] = "Banana"
hashMap[3] = "Cherry"
println("Before clearing - Size: ${hashMap.size}")
hashMap.clear()
println("After clearing - Size: ${hashMap.size}")
if (hashMap.isEmpty()) {
println("HashMap is empty")
} else {
println("HashMap is not empty")
}
}
When you run this example, the output will be:
Before clearing - Size: 3
After clearing - Size: 0
HashMap is empty
This confirms that all elements have been cleared from the HashMap.
That's it! You now know how to clear all elements from a HashMap in Kotlin.