Open In App

Kotlin Map : mapOf()

Improve
Improve
Like Article
Like
Save
Share
Report

Kotlin map is a collection that contains pairs of objects. Map holds the data in the form of pairs which consists of a key and a value. Map keys are unique and the map holds only one value for each key. 

Kotlin distinguishes between immutable and mutable maps. Immutable maps created with mapOf() means these are read-only and mutable maps created with mutableMapOf() means we can perform read and write both.

Syntax: 

fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> 
  • The first value of the pair is the key and the second is the value of the corresponding key.
  • If multiple pair have same key then map will return the last pair value.
  • The map entries is traversed in the specified order.

Kotlin program of mapOf() 

Kotlin




fun main(args : Array<String>)
{
    // declaring a map of integer to string
    val map = mapOf(1 to "Geeks", 2 to "for", 3 to "Geeks")
        // printing the map
        println(map)
}


Output: 

{1=Geeks, 2=for, 3=Geeks}

Map keys, values and entries:

Kotlin




fun main(args: Array<String>)
{
    //declaring a map of integer to string
    val map = mapOf(1 to "One", 2 to "Two" , 3 to "Three", 4 to "Four")
 
    println("Map Entries : "+map)
 
    println("Map Keys: "+map.keys )
 
    println("Map Values: "+map.values )
}


Output: 

Map Entries : {1=One, 2=Two, 3=Three, 4=Four}
Map Keys: [1, 2, 3, 4]
Map Values: [One, Two, Three, Four] 

Map Size –

We can determine the size of map using two methods. By using the size property of the map and by using the count() method. 

Kotlin




fun main() {
 
    val ranks = mapOf(1 to "India",2 to "Australia",3 to "England",4 to "Africa")
    //method 1
    println("The size of the map is: "+ranks.size)
    //method 2
    println("The size of the map is: "+ranks.count())
}


Output: 

The size of the map is: 4
The size of the map is: 4 

Empty Map –

We can create an empty serialize-able map using mapOf()

Example 2: mapOf() 

Kotlin




fun main(args: Array<String>)
{
    //here we have created an empty map using mapOf()
    val map1 = mapOf<String , Int>()
      
    println("Entries: " + map1.entries)  //entries of map
  
    println("Keys:" + map1.keys)  //keys of map
  
    println("Values:" + map1.values)  //values of map
  
}


Output: 

Entries: []
Keys:[]
Values:[] 

Get values of Map –

We can retrieve values from a map using different methods discussed in the below program. 

Kotlin




fun main() {
 
    val ranks = mapOf(1 to "India",2 to "Australia",3 to "England",4 to "Africa")
 
    //method 1
    println("Team having rank #1 is: "+ranks[1])
    //method 2
    println("Team having rank #3 is: "+ranks.getValue(3))
    //method 3
    println("Team having rank #4 is: "+ranks.getOrDefault(4, 0))
    // method  4
    val team = ranks.getOrElse(2 ,{ 0 })
    println(team)
}


Output: 

Team having rank #1 is: India
Team having rank #3 is: England
Team having rank #4 is: Africa
Australia

Map Contains Key or Values –

We can determine that a map contains a key or value using the containsKey() and containsValue() methods respectively. 

Kotlin




fun main() {
    val colorsTopToBottom = mapOf("red" to 1, "orange" to 2, "yellow" to 3,
        "green" to 4 , "blue" to 5, "indigo" to 6, "violet" to 7)
    var color = "yellow"
    if (colorsTopToBottom.containsKey(color)) {
        println("Yes, it contains color $color")
    } else {
        println("No, it does not contain color $color")
    }
    val value = 8
    if (colorsTopToBottom.containsValue(value)) {
        println("Yes, it contains value $value")
    } else {
        println("No, it does not contain value $value")
    }
}


Output: 

Yes, it contains color yellow
No, it does not contain value 8 

Two values and same key:

If two values have same key value , then the map will contain the last value of the those numbers.

Example 3: mapOf() 

Kotlin




fun main(args: Array<String>)
{
    //lets make two values with same key
    val map = mapOf(1 to "geeks1",2 to "for" , 1 to "geeks2")
    // return the map entries
    println("Entries of map : " + map.entries)
}


Output:  

Entries of map : [1=geeks2, 2=for]

Explanation: 

Here key value 1 has been initialized with two values: geeks1 and geeks2, but as we know that mapOf() can have only one value for one key item, therefore the last value is only stored by the map, and geeks1 is eliminated.

mapOf() is a function in Kotlin that creates a new read-only map. A map is a collection of key-value pairs where each key is unique.

Here’s an example of using mapOf() to create a map of strings:

Kotlin




fun main() {
    // create a new map
    val names = mapOf("John" to 25, "Mary" to 30, "Bob" to 20)
 
    // get the value associated with a key
    val johnAge = names["John"]
 
    // check if a key is present in the map
    val containsMary = names.containsKey("Mary")
 
    // print the map and the result of the contains check
    println("Names: $names")
    println("Contains Mary: $containsMary")
}


Output:

Names: {John=25, Mary=30, Bob=20}
Contains Mary: true
 

In this example, we create a new read-only map of strings using the mapOf() function with the key-value pairs “John” to 25, “Mary” to 30, and “Bob” to 20. We then retrieve the value associated with the key “John” using the square bracket notation and store it in the variable johnAge. Finally, we check if the map contains the key “Mary” using the containsKey() function and print the result to the console.

Advantages of mapOf():

  1. The map data structure provides a way to associate a key with a value, which is useful for organizing and retrieving data.
  2. The mapOf() function is easy to use and provides a simple way to create a new read-only map with initial key-value pairs.
  3. The read-only nature of the map makes it safe to pass between functions and threads without worrying about concurrent modifications.

Disadvantages of mapOf():

  1. The read-only nature of the map means that it cannot be modified once it is created. To add or remove elements, you must create a new map or use a mutable map.
  2. The map data structure can become inefficient if the number of key-value pairs is very large, as it requires O(n) time to search for a key in the worst case. If you need to perform frequent lookups or modifications, a different data structure such as a hash table or a binary tree may be more appropriate.


Last Updated : 17 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads