Kotlin Map

In this tutorial, we will talk about Kotlin Map with the help of simple examples.

Map

Maps are used to store key and value pairs. In Map:

  • key and value are user defined.
  • The key should be unique and only one value can be stored for each unique key.
  • Values can be duplicate.
  • A key value pair is also known as an entry.
  • The key and value can be of different data type.

Map are of two types, immutable map (cannot be modified) and mutable map (can be modified).

Immutable Map

The immutable map also known as read-only map support only read-only access to the map.

Immutable map are created using mapOf() and mapOf<K, V>() functions.

Create and initialize map 

The below example show you how to:

  • initialize Map using mapOf() (contains key and value of any data type), mapOf<K, V>() (contains keys and values of K and V data types).
  • create new Map from another Map with the same entries using toMap() function.
fun main() {
    val map1 = mapOf("Rank" to 1, 1 to "First", 'A' to 4)
    val map2 = mapOf<Int, String>(1 to "One", 2 to "Two", 3 to "Three", 4 to "Four")
    val map3 = map2.toMap();
    println("map1: $map1")
    // map1: {Rank=1, 1=First, A=4}
    println("map2: $map2")
    // map2: {1=One, 2=Two, 3=Three, 4=Four}
    println("map3: $map3") 
    // map3: {1=One, 2=Two, 3=Three, 4=Four}
}

Map size

The below example show you how to:

  • find the size of a Map using size property or count() method.
val marks = mapOf<String, Int>("Physics" to 80, "Maths" to 97, "Biology" to 89, "Chemistry" to 95)

println("Size of map: ${marks.size}")
//Size of map: 4
println("Size of map using count(): ${marks.count()}")
//Size of map using count(): 4

Retrieve Map keys and values 

The below example show you how to:

val marks = mapOf<String, Int>("Physics" to 80, "Maths" to 97, "Biology" to 89, "Chemistry" to 95)

println("Set of keys: ${marks.keys}")
//Set of keys: [Physics, Maths, Biology, Chemistry]
println("Set of values: ${marks.values}")
//Set of values: [80, 97, 89, 95]
println("Set of entries: ${marks.entries}")
//Set of entries: [Physics=80, Maths=97, Biology=89, Chemistry=95]
println("Marks in Physics: ${marks.get("Physics")}")
//Marks in Physics: 80
println("Marks in English: ${marks["English"]}")
//Marks in English: null
println("Marks in Maths: ${marks.getValue("Maths")}")
//Marks in Maths: 97
println("Marks in English: ${marks.getOrDefault("English", -1)}")
//Marks in English: -1
println("Marks in English: ${marks.getOrElse("English", { null })}")
//Marks in English: null

Map Contains Key or Values

The below example show you how to:

val marks = mapOf<String, Int>("Physics" to 80, "Maths" to 97, "Biology" to 89, "Chemistry" to 95)

println("Does map contains Physics: ${marks.containsKey("Physics")}")
//Does map contains Physics: true
println("Does map contains C++: ${marks.contains("C++")}")
//Does map contains C++: false
println("Does map contains Chemistry: ${"Chemistry" in marks}")
//Does map contains Chemistry: true
println("Does any subject has 80 marks: ${marks.containsValue(80)}")
//Does any subject has 80 marks: true

Map any function

The any() method returns true if at least one entry matches the given predicate.

val marks = mapOf<String, Int>("Physics" to 80, "Maths" to 97, "Biology" to 89, "Chemistry" to 95)
val value = 80
val hasValue = marks.any { it.value == value }

if (hasValue) {
    println("The map has value $value")  //The map has value 80
} else {
    println("The map does not have value $value")
}

Map Plus and minus operators

The below example show you how to:

  • replace or add an entry to a map from a given key-value pair or entries to a map from another map using plus() /operator(+).
  • remove entry with the given key or a collection of keys: list, set, and so on using minus() /operator(-).
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)

println(numbersMap + Pair("four", 4)) 
//numbersMap.plus(Pair("four", 4))
//{one=1, two=2, three=3, four=4}
println(numbersMap + Pair("one", 10))
//{one=10, two=2, three=3}
println(numbersMap + mapOf("five" to 5, "one" to 11))
//numbersMap.plus(mapOf("five" to 5, "one" to 11))
//{one=11, two=2, three=3, five=5}
println(numbersMap - "one")   
//numbersMap.minus("one")
//{two=2, three=3}

Filter Map

The below example show you how to filter map:

  • using filter(): filter map entries using both keys and values.
  • using filterKeys():  filter map entries using only keys.
  • using filterValues(): filter map entries using only values.
val items = mapOf("A" to 90, "B" to 80, "C" to 70, "D" to 60, "E" to 50)

val filtered = items.filterKeys { it == "A" || it == "C" }
println(filtered)   //{A=90, C=70}
  
val filtered2 = items.filterValues { it >= 70 }
println(filtered2) //{A=90, B=80, C=70}

val filtered3 = items.filter { it.key == "A" || it.value == 50 }
println(filtered3)   //{A=90, E=50}

Mutable Map

MutableMap inherites Map and supports read/write access, you can add, update or remove entries.

Mutable map are created using mutableMapOf() and mutableMapOf()<K,V>() functions.

Create and initialize MutableMap 

The below example show you how to:

  • initialize MutableMap using mutableMapOf() (contains key and value of any data type), mutableMapOf()<K,V>() (contains keys and values of K and V data types).
  • create new MutableMap from another MutableMap with the same entries using toMutableMap() function.
 val map1 = mutableMapOf("Rank" to 1, 1 to "First", 'A' to 4)
    val map2 = mutableMapOf<Int, String>(1 to "One", 2 to "Two", 3 to "Three", 4 to "Four")
    val map3 = map2.toMutableMap()
    println(map1)  // {Rank=1, 1=First, A=4}
    println(map2)  // {1=One, 2=Two, 3=Three, 4=Four}
    println(map3)   // {1=One, 2=Two, 3=Three, 4=Four}
}

Add items to MutableMap

The below example shows how to:

  • add the specified key value pair to the map using put(K,V) /operator []. If key already exists it will replace the value.
  • add the specified key value pair to the map only if key does not exist earlier using putIfAbsent().
  • update a map with key/value pairs from the specified map using putAll(Map< K, V >).

  • append or replace all entries from the given map in a mutable map using plusAssign()/operator(+=).
val numMap = mutableMapOf<Int, String>(1 to "One", 2 to "Two")
numMap.put(2, "two")
println(numMap)  //{1=One, 2=two}
numMap[3] = "three"
println(numMap)  //{1=One, 2=two, 3=three}
numMap.putIfAbsent(4, "four")
println(numMap)  //{1=One, 2=two, 3=three, 4=four}
numMap.putIfAbsent(1, "one")
println(numMap)  //{1=One, 2=two, 3=three, 4=four}
numMap.putAll(mapOf(5 to "five"))
println(numMap) //{1=One, 2=two, 3=three, 4=four, 5=five}
numMap += mapOf(6 to "six")
//another way of doing numMap += mapOf(6 to "six")
//numMap.plusAssign(mapOf(6 to "six"))
println(numMap)
//{1=One, 2=two, 3=three, 4=four, 5=five, 6=six}

Update/Replace item in MutableList

The below example show you how to:

  • replace the entry for the specified key only if it is currently mapped to some value using replace( K , V ).
  • replace the entry for the specified key only if currently mapped to the specified value using replace( K , oldV , newV).
val numMap = mutableMapOf<Int, String>(1 to "One", 2 to "Two")
println(numMap)  //{1=One, 2=Two}
numMap.replace(1, "one")
println(numMap)  //{1=one, 2=Two}
numMap.replace(2, "Two", "two")
println(numMap)  //{1=one, 2=two}

Remove items from MutableList

The below example show you how to:

  • remove the specified key and its corresponding value from this map
    using remove( K ).
  • remove the entry with the given key from this mutable map
    using minusAssign() or operator(-=).
  • remove the entry for the specified key only if it is mapped to the specified value
    using remove( K, V ).
  • remove all the items using clear()
val numMap = mutableMapOf<Int, String>(1 to "One", 3 to "Three", 4 to "Four", 5 to "Five", 6 to "Six")
println(numMap) //{1=One, 3=Three, 4=Four, 5=Five, 6=Six}
numMap.remove(6)
println(numMap) //{1=One, 3=Three, 4=Four, 5=Five}
numMap -= 5
//another way of doing numMap -= 5
//numMap.minusAssign(5)
println(numMap)  //{1=One, 3=Three, 4=Four}
numMap.remove(4, "four")
println(numMap)  //{1=One, 3=Three, 4=Four}
numMap.clear()
println(numMap)  //{}

Iterate over Map in Kotlin

The example show you how to iterate over a Map using:

  • for loop
  • forEach() function.
  • map function.
  • Iterator and a while loop.
val numMap = mapOf(1 to "One", 2 to "Two", 3 to "Three")

print("print map using for loop: ")
for ((key, value) in numMap) {
    print(" $key = $value ") 
}
println()

print("print map using forEach function: ")
numMap.forEach { (key, value) -> print(" $key = $value ") }
println()

print("print map using map function: ")
numMap.map { (key, value) -> print(" $key = $value ") }
println()

print("print map using Iterator: ")
val iterator = numMap.keys.iterator()

while (iterator.hasNext()) {
    val key = iterator.next()
    val value = numMap[key]
    print(" $key = $value ")
}
println()

Output:

print map using for loop:  1 = One  2 = Two  3 = Three
print map using forEach loop:  1 = One  2 = Two  3 = Three
print map using map function:  1 = One  2 = Two  3 = Three
print map using Iterator:  1 = One  2 = Two  3 = Three

Leave a Reply