Kotlin - Maps


Kotlin map is a collection of key/value pairs, where each key is unique, and it can only be associated with one value. The same value can be associated with multiple keys though. We can declare the keys and values to be any type; there are no restrictions.

A Kotlin map can be either mutable (mutableMapOf) or read-only (mapOf).

Maps are also known as dictionaries or associative arrays in other programming languages.

Creating Kotlin Maps

For map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for mutable maps.

A read-only view of a mutable map can be obtained by casting it to Map.

Example

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    println(theMap)
    
    val theMutableMap = mutableSetOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    println(theMutableMap)
}

When you run the above Kotlin program, it will generate the following output:

{one=1, two=2, three=3, four=4}
[(one, 1), (two, 2), (three, 3), (four, 4)]

Creating Map using HashMap

A Kotlin map can be created from Java's HashMap.

Example

fun main() {
    val theMap = HashMap<String, Int>()
    
    theMap["one"] = 1
    theMap["two"] = 2
    theMap["three"] = 3
    theMap["four"] = 4
    
    println(theMap)
}

When you run the above Kotlin program, it will generate the following output:

{four=4, one=1, two=2, three=3}

Using Pair while Creating Map

We can use Pair() method to create key/value pairs:

Example

fun main() {
    val theMap = mapOf(Pair("one", 1), Pair("two", 2), Pair("three", 3))
    println(theMap)
}

When you run the above Kotlin program, it will generate the following output:

{one=1, two=2, three=3}

Kotlin Properties

Kotlin map has properties to get all entries, keys, and values of the map.

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
    println("Entries: " + theMap.entries)
    println("Keys:" + theMap.keys)
    println("Values:" + theMap.values)
}

When you run the above Kotlin program, it will generate the following output:

Entries: [one=1, two=2, three=3, four=4]
Keys:[one, two, three, four]
Values:[1, 2, 3, 4]

Loop through Kotlin Maps

There are various ways to loop through a Kotlin Maps. Lets study them one by one:

Using toString() function

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    println(theMap.toString())
}

When you run the above Kotlin program, it will generate the following output:

{one=1, two=2, three=3, four=4}

Using Iterator

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
    val itr = theMap.keys.iterator()
    while (itr.hasNext()) {
        val key = itr.next()
        val value = theMap[key]
        println("${key}=$value")
    }
}

When you run the above Kotlin program, it will generate the following output:

one=1
two=2
three=3
four=4

Using For Loop

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
   for ((k, v) in theMap) {
      println("$k = $v")
   }
   
}

When you run the above Kotlin program, it will generate the following output:

one = 1
two = 2
three = 3
four = 4

Using forEach

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
   theMap.forEach { 
      k, v -> println("Key = $k, Value = $v") 
   }
}

When you run the above Kotlin program, it will generate the following output:

Key = one, Value = 1
Key = two, Value = 2
Key = three, Value = 3
Key = four, Value = 4

Size of Kotlin Map

We can use size property or count() method to get the total number of elements in a map:

Example

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
    println("Size of the Map " + theMap.size)
    println("Size of the Map " + theMap.count())
}

When you run the above Kotlin program, it will generate the following output:

Size of the Map 4
Size of the Map 4

The containsKey() & containsValue() Methods

The The containsKey() checks if the map contains a key. The containsValue() checks if the map contains a value.

Example

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)

   if(theMap.containsKey("two")){
      println(true)
   }else{
      println(false)
   }
   
   if(theMap.containsValue("two")){
      println(true)
   }else{
      println(false)
   } 
}

When you run the above Kotlin program, it will generate the following output:

true
false

The isEmpty() Method

The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise.

Example

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
   if(theMap.isEmpty()){
      println(true)
   }else{
      println(false)
   }
}

When you run the above Kotlin program, it will generate the following output:

false

The get() Method

The get() method can be used to get the value corresponding to the given key. The shorthand [key] syntax is also supported.

Example

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)

   println("The value for key two " + theMap.get("two"))
   println("The value for key two " + theMap["two"])
}

When you run the above Kotlin program, it will generate the following output:

The value for key two 2
The value for key two 2
There is also the function getValue() which has slightly different behavior: it throws an exception if the key is not found in the map.

Map Addition

We can use + operator to add two or more maps into a single set. This will add second map into first map, discarding the duplicate elements.

If there are duplicate keys in two maps then second map's key will override the previous map key.

Example

fun main() {
    val firstMap = mapOf("one" to 1, "two" to 2, "three" to 3)
    val secondMap = mapOf("one" to 10, "four" to 4)
    val resultMap = firstMap + secondMap
    
    println(resultMap)
}

When you run the above Kotlin program, it will generate the following output:

{one=10, two=2, three=3, four=4}

Map Subtraction

We can use - operator to subtract a list from a map. This operation will remove all the keys of the list from the map and will return the result.

Example

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3)
    val theKeyList = listOf("one", "four")
    val resultMap = theMap - theKeyList
    
    println(resultMap)
}

When you run the above Kotlin program, it will generate the following output:

{two=2, three=3}

Removing Entries from Map

We can use remove() method to remove the element from a mutable map, or we can use minus-assign (-=) operator to perform the same operation

Example

fun main() {
    val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    theMap.remove( "two")
    println(theMap)
    
    theMap -= listOf("three")
    println(theMap)
}

When you run the above Kotlin program, it will generate the following output:

{one=1, three=3, four=4}
{one=1, four=4}

Sorting Map Elements

We can use toSortedMap() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order.

You can also create a sorted map with the given key/values using sortedMapOf() method. Just use this method in place of mapOf().

Example

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    var resultMap = theMap.toSortedMap()
    println(resultMap)
}

When you run the above Kotlin program, it will generate the following output:

{four=4, one=1, three=3, two=2}

Filtering Map Elements

We can use either filterKeys() or filterValues() method to filter out the entries.

We can also use filter() method to filter out the elements matching the both key/value

.

Example

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    var resultMap = theMap.filterValues{ it > 2}
    println(resultMap)
    
    resultMap = theMap.filterKeys{ it == "two"}
    println(resultMap)
    
    resultMap = theMap.filter{ it.key == "two" || it.value == 4}
    println(resultMap)
    
}

When you run the above Kotlin program, it will generate the following output:

{three=3, four=4}
{two=2}
{two=2, four=4}

Mapping Map Elements

We can use map() method to map all elements using the provided function:.

Example

fun main() {
     val theMap = mapOf("one" to 1, "two" to 2, "three" to 3)
    val resultMap = theMap.map{ (k, v) -> "Key is $k, Value is $v" }
    
    println(resultMap)
}

When you run the above Kotlin program, it will generate the following output:

[Key is one, Value is 1, Key is two, Value is 2, Key is three, Value is 3]

Kotlin Mutable Map

We can create mutable set using mutableMapOf(), later we can use put to add more elements in the same map, and we can use remove() method to remove the elements from the set.

Example

fun main() {
     val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
    theMap.put("four", 4)
    println(theMap)
    
    theMap["five"] = 5
    println(theMap)
    
    theMap.remove("two")
    println(theMap)
    
}

When you run the above Kotlin program, it will generate the following output:

{one=1, two=2, three=3, four=4}
{one=1, two=2, three=3, four=4, five=5}
{one=1, three=3, four=4, five=5}

Quiz Time (Interview & Exams Preparation)

Q 1 - Can we make a mutable Kotlin map as immutable?

A - Yes

B - No

Answer : A

Explanation

Yes we can make a mutable set to immutable by casting them to Map

Q 2 - We can add two or more maps and create a single set using + operator:

A - True

B - False

Answer : A

Explanation

Yes we can add or subtract two Kotlin maps and generate a third set. A plus sign works like a union() for set.

Q 2 - Which method will return the value for the given key of Kotlin Map?

A - get()

B - elementAt()

C - Direct index with set variable

D - None of the above

Answer : A

Explanation

get() method is used to get the value corresponding to a key.

Advertisements