Skip to main content

How to copy a HashMap to another HashMap in Kotlin

How to copy a HashMap to another HashMap in Kotlin.

Here's a step-by-step tutorial on how to copy a HashMap to another HashMap in Kotlin:

Step 1: Create the source HashMap

To begin, create a HashMap that you want to copy to another HashMap. You can add key-value pairs using the put method:

val sourceMap = HashMap<Int, String>()
sourceMap.put(1, "Apple")
sourceMap.put(2, "Banana")
sourceMap.put(3, "Orange")

Step 2: Create the destination HashMap

Next, create an empty HashMap that will hold the copied key-value pairs:

val destinationMap = HashMap<Int, String>()

Step 3: Use the putAll() method

To copy the elements from the source HashMap to the destination HashMap, you can use the putAll method. This method takes another Map or HashMap as a parameter and copies all the key-value pairs into the destination HashMap:

destinationMap.putAll(sourceMap)

Step 4: Verify the copied HashMap

You can check if the elements were successfully copied by iterating over the destination HashMap and printing the key-value pairs:

for ((key, value) in destinationMap) {
println("Key: $key, Value: $value")
}

Here's the complete code:

val sourceMap = HashMap<Int, String>()
sourceMap.put(1, "Apple")
sourceMap.put(2, "Banana")
sourceMap.put(3, "Orange")

val destinationMap = HashMap<Int, String>()
destinationMap.putAll(sourceMap)

for ((key, value) in destinationMap) {
println("Key: $key, Value: $value")
}

This will output:

Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Orange

That's it! You have successfully copied a HashMap to another HashMap in Kotlin using the putAll method.