(Translated by https://www.hiragana.jp/)
Kotlin Map : mapOf() | GeeksforGeeks
Open In App

Kotlin Map : mapOf()

Last Updated : 25 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Kotlin, a Map is a collection that stores data in key-value pairs. Each key in a map is unique, and the map holds only one value for each key. If a key is repeated, only the last value is retained.

Kotlin distinguishes between:

  1. Immutable maps (mapOf()) - read-only
  2. Mutable maps (mutableMapOf()) - read and write supported

Syntax: 

fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V>
  • K: Type of keys
  • V: Type of values
  • Pair<K, V>: Each key-value entry
  • Returns a new read-only map

If multiple entries use the same key, only the last value is kept.

Example of mapOf() -

fun main() {
    val map = mapOf(1 to "Geeks", 2 to "for", 3 to "Geeks")
    println(map)
}

Output: 

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

Accessing Keys, Values, and Entries -

fun main() {
    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. 

fun main() {
    val ranks = mapOf(1 to "India",2 to "Australia",3 to "England",4 to "Africa")
    println("The size of the map is: "+ranks.size)
    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 map using mapOf() with no arguments.

Example -

fun main() {
    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:[]

Getting Values from a Map -

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

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. 

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

Duplicate Keys Example -

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

Example 3: mapOf() 

fun main() {
    val map = mapOf(
        1 to "geeks1",
        2 to "for", 
        1 to "geeks2"
    )
    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.

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

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.

Next Article
Article Tags :

Similar Reads