Mutable maps

The mutable map supports adding and removing pairs, and provides a number of functions to update the existing collections. We can create a mutable map by using the mutableMapOf function:

val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"), Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three"))

Take a look at the following diagram of the MutableMap interface:

The mutable map provides the following functions:

  • put(Pair): This function inserts a pair at the end of the map:
val result = map.put(4 ,"Four")

It returns null if the new pair is successfully inserted. Maps can't contain duplicate keys, so if the key already exists, the put function will replace the value with the existing one and return the value of the existing key:

var result = map.put(4 ,"Four")
result = map.put(4 ,"FOUR")
println(map)
println(result)
  • remove(key): This function is used to remove a pair from a map using a key. It returns null if the pair is successfully removed, otherwise it returns null.
  • remove(key,value): While the remove(key) function removes the pair from the map, the remove(key,value) function goes one step further and asks for both the key and the value to make sure that the desired pair is removed. It returns true if it is successful, otherwise it returns false:
fun mutableMapRemove(){

val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"),Pair(2,"Two"), Pair(3,"Three"), Pair(4,"Four"))
println(map)

var result = map.remove(4)
println("Remove " + result)

var success = map.remove(2,"Two")
println("Remove " + success)

println(map)
}
  • clear(): The clear function removes all pairs from the map. Although it removes all the elements, it doesn't remove the map itself.
  • putAll(): The putAll function is used to add an independent map in an existing one:
fun clearAndPutAll(){

val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three"))
println(map)

val miniMap = mapOf(Pair(4,"Four"),Pair(5,"Five"))
map.putAll(miniMap)
println(map)

map.clear()
println(map)

map.putAll(miniMap)
println(map)
}

First, create a map and display it on the screen. Then, create another map and add it in the existing one using the putAll function. After that, verify the main map by printing it on the screen. Once you have finished, clear the map using the clear function and add miniMap using the putAll function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.221