Kotlin Maps

Introduction

Maps in Kotlin are collections of key-value pairs where each key is unique, and each key maps to exactly one value.

Maps are useful for storing data that can be quickly retrieved using a key.

Kotlin provides two types of maps:

  • Map for immutable maps.
  • MutableMap for mutable maps.

This chapter will cover how to create and manipulate both immutable and mutable maps, along with common operations that can be performed on maps.

Immutable Maps

An immutable map cannot be modified after it is created. You can use the mapOf function to create an immutable map.

Creating an Immutable Map

Syntax

val map: Map<KeyType, ValueType> = mapOf(key to value, ...)

Example

fun main() {
    val fruits: Map<String, Int> = mapOf("Apple" to 1, "Banana" to 2, "Cherry" to 3)
    println(fruits)
}

Explanation:

  • val fruits: Map<String, Int> = mapOf("Apple" to 1, "Banana" to 2, "Cherry" to 3): Creates an immutable map of strings to integers.

Output:

{Apple=1, Banana=2, Cherry=3}

Mutable Maps

A mutable map can be modified after it is created. You can use the mutableMapOf function to create a mutable map.

Creating a Mutable Map

Syntax

val map: MutableMap<KeyType, ValueType> = mutableMapOf(key to value, ...)

Example

fun main() {
    val fruits: MutableMap<String, Int> = mutableMapOf("Apple" to 1, "Banana" to 2)
    fruits["Cherry"] = 3
    println(fruits)
}

Explanation:

  • val fruits: MutableMap<String, Int> = mutableMapOf("Apple" to 1, "Banana" to 2): Creates a mutable map of strings to integers.
  • fruits["Cherry"] = 3: Adds a key-value pair to the mutable map.

Output:

{Apple=1, Banana=2, Cherry=3}

Common Map Operations

Kotlin provides various operations that can be performed on maps, such as accessing values, iterating through maps, adding/removing entries, and more.

Accessing Values

You can access values in a map using the key.

Example

fun main() {
    val fruits: Map<String, Int> = mapOf("Apple" to 1, "Banana" to 2, "Cherry" to 3)
    println(fruits["Apple"])  // Prints "1"
    println(fruits["Mango"])  // Prints "null"
}

Output:

1
null

Iterating Through a Map

You can iterate through a map using a for loop.

Example

fun main() {
    val fruits: Map<String, Int> = mapOf("Apple" to 1, "Banana" to 2, "Cherry" to 3)
    for ((key, value) in fruits) {
        println("$key: $value")
    }
}

Output:

Apple: 1
Banana: 2
Cherry: 3

Adding and Removing Entries (Mutable Map)

You can add and remove entries from a mutable map using various methods.

Example

fun main() {
    val fruits: MutableMap<String, Int> = mutableMapOf("Apple" to 1, "Banana" to 2)
    fruits["Cherry"] = 3
    println(fruits) // Prints "{Apple=1, Banana=2, Cherry=3}"

    fruits.remove("Banana")
    println(fruits) // Prints "{Apple=1, Cherry=3}"
}

Output:

{Apple=1, Banana=2, Cherry=3}
{Apple=1, Cherry=3}

Checking Keys and Values

You can check if a map contains a specific key or value using the containsKey and containsValue methods.

Example

fun main() {
    val fruits: Map<String, Int> = mapOf("Apple" to 1, "Banana" to 2, "Cherry" to 3)
    println(fruits.containsKey("Apple"))   // Prints "true"
    println(fruits.containsValue(2))       // Prints "true"
    println(fruits.containsKey("Mango"))   // Prints "false"
    println(fruits.containsValue(5))       // Prints "false"
}

Output:

true
true
false
false

Filtering

You can filter entries in a map based on a condition.

Example

fun main() {
    val fruits: Map<String, Int> = mapOf("Apple" to 1, "Banana" to 2, "Cherry" to 3)
    val filteredFruits = fruits.filter { (key, value) -> value > 1 }
    println(filteredFruits) // Prints "{Banana=2, Cherry=3}"
}

Output:

{Banana=2, Cherry=3}

Transforming

You can transform entries in a map using the map or mapValues functions.

Example

fun main() {
    val fruits: Map<String, Int> = mapOf("Apple" to 1, "Banana" to 2, "Cherry" to 3)
    val transformedFruits = fruits.mapValues { (key, value) -> value * value }
    println(transformedFruits) // Prints "{Apple=1, Banana=4, Cherry=9}"
}

Output:

{Apple=1, Banana=4, Cherry=9}

Example Program with Maps

Here is an example program that demonstrates various aspects of using maps in Kotlin:

fun main() {
    // Immutable map
    val fruits: Map<String, Int> = mapOf("Apple" to 1, "Banana" to 2, "Cherry" to 3)
    println(fruits)

    // Mutable map
    val mutableFruits: MutableMap<String, Int> = mutableMapOf("Apple" to 1, "Banana" to 2)
    mutableFruits["Cherry"] = 3
    println(mutableFruits)

    // Accessing values
    println(fruits["Apple"])
    println(fruits["Mango"])

    // Iterating through a map
    for ((key, value) in fruits) {
        println("$key: $value")
    }

    // Adding and removing entries (mutable map)
    mutableFruits.remove("Banana")
    println(mutableFruits)

    // Checking keys and values
    println(fruits.containsKey("Apple"))
    println(fruits.containsValue(2))
    println(fruits.containsKey("Mango"))
    println(fruits.containsValue(5))

    // Filtering
    val filteredFruits = fruits.filter { (key, value) -> value > 1 }
    println(filteredFruits)

    // Transforming
    val transformedFruits = fruits.mapValues { (key, value) -> value * value }
    println(transformedFruits)
}

Output:

{Apple=1, Banana=2, Cherry=3}
{Apple=1, Banana=2, Cherry=3}
1
null
Apple: 1
Banana: 2
Cherry: 3
{Apple=1, Cherry=3}
true
true
false
false
{Banana=2, Cherry=3}
{Apple=1, Banana=4, Cherry=9}

Conclusion

In this chapter, you learned about maps in Kotlin, including how to create and manipulate immutable and mutable maps. You also learned about common map operations such as accessing values, iterating through maps, adding/removing entries, checking keys and values, filtering, and transforming. Understanding and using maps effectively is crucial for writing robust and maintainable Kotlin programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top