Kotlin Map and MutableMap Collections Tutorial

  • Post author:
  • Post category:Kotlin

In this section, we will learn what the Map and MutableMap are and how to use them in Kotlin.

What is Map Collection in Kotlin?

A Map object represents a collection like Arrays and Lists where we can store values (objects) there.

But here’s the difference between a Map object compared to Arrays and Lists:

In Arrays and Lists, we use a preset index number in order to access the elements within an Array or List. Basically, the index number acts as the key by which we find values in these types of objects.

But when it comes to Maps, we’re in charge of creating a key for each value as well! The beauty of using keys is that you can use types other than Int! For example, we can use String values as the keys in a Map object, which is easier to remember, and then in later times we can use those keys to invoke the values in a Map object.

Perhaps a real world example of Maps would be a Telephone Directory where you can see a name attached to each phone number! So the names here act as the key and the phone numbers are the values associated with each name.

Notes:

  • The keys in a Map object must be unique. But their values can be duplicated.
  • Each pair of key-value pair is called an entry.
  • The size of a Map object is static! Meaning after creating the map and setting its values, you can’t increase or decrease the size.

How to create a Map object in Kotlin? Kotlin mapOf() Function:

In order to create a Map object in Kotlin, we use the mapOf() function.

This is the syntax of how we use this function:

mapOf( key to value, key1 to value1, key_n to value_n)

key: This is the key that we use in order to access the related value. It could be of type Int, String, Boolean, etc.

value: this is the related value associated with each key. Basically, values are the reason why we use keys in Maps.

to: we use the to keyword to separate keys from values.

,: in order to separate each entry from another one we use a comma.

Note that Maps are generics with two generic names! This is their syntax:

Map<T,E>

The first generic name is related to the type of the keys and the second generic name relates to the data type of values.

Now if you create a variable with the data type like:

Map<String,String>

This means the keys and values we set as the arguments of the mapOf() function must both be of type String.

Or for example if we set the data type of a variable to:

Map<Any, Any>

This means the type of keys and values we set for the mapOf() object could be of any type.

Example: creating a Map object in Kotlin using mapOf() Function:

fun main(){

    var map = mapOf(10 to 20, "Omid" to 100, true to false)

    println(map.toString())

}

Output:

{10=20, Omid=100, true=false}

Note that in this example, the keys and values of each entry are of different types! This means the data type of the map variable will be:

Map<Any, Any>

How to Access Elements of a Map Object?

There are two methods to access the values of a Map object:

  • The first one is to use a pair of brackets [], put it after the name of a map object and then put the key name that we want to get its value in the map.

For example:

map[key-name]
  • The second method of accessing the values of a map is by calling the getValue() function.

This function takes a key-name as its argument and returns the related value associated with the key.

Note: when using a pair of bracket, if the specified key didn’t exist in the target map, the value null will return instead. But if you’re using the getValue() function and the target key didn’t exist in the map, then the NoSuchElementException exception will be thrown as a result.

Example: accessing the elements of a Map object

fun main(){
    var map = mapOf(10 to 20, "Omid" to 100, true to false)

    println(map[10])
    println(map["Omid"])
    println(map["Jack"])

    println(map.getValue(true))
    //println(map.getValue("John")) *If we call this function using the value John, and exception will be thrown
}

Output:

20

100

null

false

Kotlin Map containsKey and containsValue Functions

The two functions containsKey and containsValue are used to see if the target map object has a specific key or value, respectively.

Basically, we set the target key as the argument of the containsKey function (or the target value as the argument of the containsValue function) now if the map had the specified key or value then the return value will be true, otherwise the value false will return instead.

Example: using containsKey and containsValue function of Kotlin Map object

fun main(){
    var map = mapOf("Omid" to "Dehghan", "Elon" to "Musk", "John" to "Doe", "Monica" to "Geller")

    if (map.containsKey("Monica")){
        println(map.getValue("Monica"))
    }

    println(map.containsValue("Musk"))
}

Output:

Geller

true

What is MutableMap Collection in Kotlin?

The Kotlin MutableMap collection works the same as Map objects, with the exception that using a MutableMap type we can create a collection that can increase or decrease its elements at runtime.

How to create a MutableMap object in Kotlin? Kotlin mutableMapOf() Function:

In order to create a MutableMap object we can use the mutalbeMapOf() function and pass the entries as the argument of this function just like the way we did for the Map objects using the mapOf() function.

Example: creating a MutableMap object in Kotlin using mutableMapOf() Function:

fun main(){

    var map = mutableMapOf("Omid" to "Dehghan", "Elon" to "Musk", "John" to "Doe", "Monica" to "Geller")

    println(map.toString())

}

Output:

{Omid=Dehghan, Elon=Musk, John=Doe, Monica=Geller}

Kotlin MutableMap: Adding Elements using put() Function

In order to add a new entry to a MutableMap object, we use the put() function.

This function takes two arguments:

  • The first one is the value of the key that we want to add to the map.
  • The second argument is the value we want to set for that key.

Note: if the target map already had the specified key, then calling this function would update the old value of the key with the new one. So basically no duplicated key will be added to the map.

Example: using MutableMap put() function in Kotlin

fun main(){
    var map = mutableMapOf("Omid" to "Dehghan", "Elon" to "Musk", "John" to "Doe", "Monica" to "Geller")

    println("The entries of the map before calling the put() function: ")
    println(map.toString())

    map.put("Jack","Bauer")
    map.put("Tony","Shark")
    map.put("Tony","Stark")
    
    println("The entries of the map after calling the put() function: ")
    println(map.toString())
}

Output:

The entries of the map before calling the put() function:

{Omid=Dehghan, Elon=Musk, John=Doe, Monica=Geller}

The entries of the map after calling the put() function:

{Omid=Dehghan, Elon=Musk, John=Doe, Monica=Geller, Jack=Bauer, Tony=Stark}

Note that because at the time of creating the map we used string values for both keys and values, the data type of the map object became Map<String,String>. This means we should know use string values for both keys and values for this object! Otherwise we will get an exception if we tried to use other data type for either key or value.

Kotlin MutableMap remove() Function

You can remove keys and values from a MutableMap object as well!

To do that, we use the remove() function.

This function has two forms.

  • For the first form, it takes only one argument and that is the target key that we want to remove the key and its value from the map.

For example:

map.remove(key-name)

So here, if the map had the specified key, that key and its value will be removed from the map. Also, the old value will be returned as a result of calling the remove function. But if the key wasn’t in the map, the value null will return as a result (meaning the operation failed).

  • For the second form, the remove() function takes two arguments:
  • The first argument is the key we want to remove from the map.
  • The second argument is the value we want to be associated with the specified key!

So, using the remove() function with two arguments, our program will first look into the target map object to find the specified key. After that, if it found the key, it will check its value to see if it matches the second argument of the function.

Now if they matched (the key and its value) then they will be removed from the map and the value true will return as a result.

But if either key or value didn’t match with the entries of the target map, then the operation will fail and the value false will return as a result.

Example: using MutableMap remove() function in Kotlin

fun main(){
    var map = mutableMapOf("Omid" to "Dehghan", "Elon" to "Musk", "John" to "Doe", "Monica" to "Geller")

    println("The entries of the map before calling the remove() function: ")
    println(map.toString())

    println(map.remove("Omid"))
    println(map.remove("Monica","Geller"))
    
    println("The entries of the map after calling the remove() function: ")
    println(map.toString())
}

Output:

The entries of the map before calling the remove() function:

{Omid=Dehghan, Elon=Musk, John=Doe, Monica=Geller}

Dehghan

true

The entries of the map after calling the remove() function:

{Elon=Musk, John=Doe}

Here, the first time we called the remove() function, we only passed one argument and that was the key Omid. Now, because this map object has this key, then the operation succeeds (the key and its value is removed from the map and the old value is returned as a result).

Now the second time of calling the remove() function, we used two arguments. This time we set the key and also the value. So here our program will look for the specified key and if it found one, then it will check its value as well. If the value matched the second argument of the function, then that key-value will be removed from the map and the boolean value true will be returned as a sign of success operation.

Kotlin MutableMap clear() Function

The clear() function is used when we want to clear the entire entries of a MutableMap object.

Simply call this function on a map object and it will remove the entire entries of that map.

Example: using MutableMap clear() function in Kotlin

fun main(){
    var map = mutableMapOf("Omid" to "Dehghan", "Elon" to "Musk", "John" to "Doe", "Monica" to "Geller")

    println("The entries of the map before calling the clear() function: ")
    println(map.toString())

    map.clear() 
    
    println("The entries of the map after calling the clear() function: ")
    println(map.toString())
}

Output:

The entries of the map before calling the clear() function:

{Omid=Dehghan, Elon=Musk, John=Doe, Monica=Geller}

The entries of the map after calling the clear() function:

{}

Kotlin MutableMap: getting Keys using keys Property

If we want to get the access to all the keys of a Map object, we can use the keys property.

This property will return a Set collection that contains the entire key elements of a map object. We can then use for loop, for example, to loop through these elements.

Example: getting keys of a MutableMap object using keys property

fun main(){
    var map = mutableMapOf("Omid" to "Dehghan", "Elon" to "Musk", "John" to "Doe", "Monica" to "Geller")

    for (key in map.keys){
        println(key)
    }
}

Output:

Omid

Elon

John

Monica

Kotlin MutableMap Object: getting values using values Property

The values property works the same as the keys property except that it returns a collection that contains all the values of the target map object.

Example: getting values of a Mutable object using values property

fun main(){
    var map = mutableMapOf("Omid" to "Dehghan", "Elon" to "Musk", "John" to "Doe", "Monica" to "Geller")

    for (value in map.values){
        println(value)
    }
}

Output:

Dehghan

Musk

Doe

Geller

Leave a Reply