Map and MutableMap

The Map interface in the collections framework is a bit different than all others interfaces we have covered earlier; unlike others it works with key-value pairs. No, this is not similar to PairPair is just a pair of two values combined together, while a map is a collection of key-value pairs.

In a map, keys are unique and cannot be duplicated. If you add two values with the same key, then the later one will replace the previous one. Values, on the other hand can be redundant/duplicate. The reason behind this behavior is that in a map, a value is stored and retrieved with respect to its key, so redundant keys will make it impossible to distinguish them from each-other and to fetch their values.

The declaration of Map in Kotlin reads like interface Map<K, out V>, the K value is the generic type of the key and V is the generic type of value.

To learn more about collections, let us have a look at a few of the functions and properties. Go through the following list:

  • val size: Int: This function indicates the size of the Map interface, that is, the number of key-value pairs residing inside the map.
  • fun isEmpty(): Boolean: This function helps in checking whether a Map interface is empty or not.
  • fun containsKey(key: K): Boolean: This function checks for the provided key inside the collection of key-value pairs it has and returns true if it is found.
  • operator fun get(key: K): V?: This function cum operator (if used by square brackets ([]) like an array) returns the value corresponding to a key or null if the key doesn't exist within it.
  • val keys: Set<K>: This function indicates the collection of keys available in that map at that point of time. As keys cannot be duplicated and they are not ordered, a Set value is the best data-structure to hold them.
  • val values: Collection<V>: Contains all the values of the map value as a collection.
  • interface Entry<out K, out V>: This function is defined inside the Map interface. An Entry represents a single key-value pair in the Map interface. The key-value pairs are stored as an entry inside the map value.
  • val entries: Set<Map.Entry<K, V>>: This function gets you all the entries in the map.

The previous were read-only interfaces of Map as it only supports read-only operations. For read-write access, you've to use the mutableMap function. So, let us now have a look at the read-write interfaces provided by mutableMap as seen in the following list:

  • fun put(key: K, value: V): V? : This interface adds a key-value pair to the Map and returns the previous value associated with the key (if any or null if the key wasn't present in the Map earlier).
  • fun remove(key: K): V? : This interface removes a key-value pair from the map with the key and returns the value and returns null if the key doesn't exist in the Map interface.
  • fun putAll(from: Map<out K, V>): Unit : This interface adds the key-value pairs from the provided map value.
  • fun clear(): Unit: As the name suggests, this instance clears the map value. It removes everything that the map value contains—every key and every value.

So, as we now know the interfaces and functions the Map interfaces has to offer, let's now have an example with Map.

Let's go through the following example:

fun main(args: Array<String>) { 
    val map = mapOf( 
            "One".to(1), 
            "Two".to(2), 
            "Three".to(3), 
            "Four".to(4), 
            "Five".to(0),//(1) We placed 0 instead of 5 here, will be replaced later 
            "Six".to(6), 
            "Five".to(5)//(2) This will replace earlier map of "Five".to(0) 
            ) 
 
    println("The value at Key `Four` is ${map["Four"]}") 
 
    println("Contents in map") 
    for(entry in map) { 
        println("Key ${entry.key}, Value ${entry.value}") 
    } 
 
    val mutableMap = mutableMapOf<Int,String>() 
 
    mutableMap.put(1,"Item 1") 
    mutableMap.put(2,"Item 2") 
    mutableMap.put(3,"Item 3") 
    mutableMap.put(4,"Item 4") 
 
    println("Replacing value at key 1 - ${mutableMap.put(1,"Item 5")}")//(3) 
 
    println("Contents in mutableMap") 
    for(entry in mutableMap) { 
        println("Key ${entry.key}, Value ${entry.value}") 
    } 
} 

So, we demonstrated the use of the following two types of maps:

  • Read-only Map
  • Read-write MutableMap

Kotlin provides you with a version of the mapOf() function that accepts vararg parameters of the Pair type. This makes it easy for you to create read-only maps—just pass the key-value pairs as the instances of Pair to the mapOf() function.

Let us see the output before further inspecting and discussing the program. See the following screenshot:

While creating the map, on comment (1), we passed a "Five".to(0) pair and on comment (2), we passed the "Five".to(5) pair to the same mapOf function, to check which value the map stores for the "Five" key; the output suggests that the map took the second value—5, as we described earlier that a map value always takes the last value for the same key.

Also note that Kotlin supports array-like square brackets in Map as well. Instead of an index, you can pass the key.

So, as we got our hands dirty with three most important interfaces in Kotlin's collection framework: List, Set, and Map. Let's now move forward and get ourselves introduced to data operations in a collection.

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

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