How to add or update an entry of the HashMap in Kotlin

Overview

The set method adds or updates an entry in the HashMap.

Syntax

operator fun <K, V> MutableMap<K, V>.set(key: K, value: V)

Argument: The key and value to be added or updated.

Return value

This method doesn’t return any value.

Code

The code below demonstrates how to add or update an entry from the HashMap.

fun main() {
//create a new LinkedHashMap which can have String type as key, and int type as value
var map : HashMap<String, Int> = HashMap<String, Int> ()
// add two entries
map.put("one", 1)
map.put("two", 2)
map.put("three", 3)
println("The map is : $map")
// updating value of an entry
println("\nUpdating the value from 1 to 10 for the entry with key-one")
map.set("one", 10);
println("The map is : $map")
// adding a new entry
println("\nAdding a new entry four-4")
map.set("four", 4);
println("The map is : $map")
}

Code explanation

Line 3: We create a new HashMap object named map.

Lines 5–7: We add three entries to the map {one=1,two=2,three=3}, using the put method.

Line 12: We use the set method with (one,10) as arguments. This method checks for the entry with the key- one. In our map, there is one entry with the key -one. Therefore, the value of the entry is updated to 10. Now the map is {one=10, two=2, three=3}.

Line 16: We use the set method with (four,4) as arguments. This method checks for the entry with the key-four. In our map, there is no entry with a key - four. Therefore a new entry {four-4} will be added to the map. Now the map is {one=10, two=2, three=3, four=4}.

Free Resources