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.
For map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for mutable maps.
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)]

A Kotlin map can be created from Java's HashMap.
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}

We can use Pair() method to create key/value pairs:
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 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]

There are various ways to loop through a Kotlin Maps. Lets study them one by one:
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}

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

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

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

We can use size property or count() method to get the total number of elements in a map:
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 The containsKey() checks if the map contains a key. The containsValue() checks if the map contains a value.
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 returns true if the collection is empty (contains no elements), false otherwise.
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 can be used to get the value corresponding to the given key. The shorthand [key] syntax is also supported.
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

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.
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}

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.
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}

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
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}

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().
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}

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
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}

We can use map() method to map all elements using the provided function:.
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]

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.
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}

Q 1 - Can we make a mutable Kotlin map as immutable?
A - Yes
B - No
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
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
get() method is used to get the value corresponding to a key.

    68 Lectures 
     4.5 hours 

 Arnab Chakraborty

    71 Lectures 
     5.5 hours 

 Frahaan Hussain

    18 Lectures 
     1.5 hours 

 Mahmoud Ramadan

    49 Lectures 
     6 hours 

 Catalin Stefan

    49 Lectures 
     2.5 hours 

 Skillbakerystudios

    22 Lectures 
     1 hours 

 CLEMENT OCHIENG
 Print
 Add Notes
 Bookmark this page