Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Kotlin Maps Tutorial

What are Maps?

A map is a collection of key-value pairs where each key is unique and is associated with one value. In Kotlin, maps are a part of the collection framework and are used to store data in a structured way.

Maps can be mutable or immutable:

  • Mutable Maps: Can change the content (add, remove, or update entries).
  • Immutable Maps: Cannot change the content once created.

Creating Maps

In Kotlin, you can create a map using the mapOf() function for immutable maps and mutableMapOf() for mutable maps.

Example:
val immutableMap = mapOf("A" to 1, "B" to 2, "C" to 3)
val mutableMap = mutableMapOf("X" to 10, "Y" to 20)

Accessing Values

You can access the values in a map using their keys.

Example:
println(immutableMap["A"]) // Output: 1
println(mutableMap["X"]) // Output: 10

Modifying Maps

Mutable maps allow you to add, remove or update entries.

Example:
mutableMap["Z"] = 30 // Adding a new entry
mutableMap["X"] = 15 // Updating an existing entry
mutableMap.remove("Y") // Removing an entry
// Current state of mutableMap after modifications:
{X=15, Z=30}

Iterating Over Maps

You can iterate over a map using a loop:

Example:
for ((key, value) in mutableMap) {
println("$key -> $value")
}

Common Map Functions

Kotlin provides several useful functions for maps:

  • containsKey(key): Checks if the map contains a specific key.
  • containsValue(value): Checks if the map contains a specific value.
  • keys: Returns a set of all keys in the map.
  • values: Returns a collection of all values in the map.
Example:
println(mutableMap.containsKey("Z")) // Output: true
println(mutableMap.values) // Output: [15, 30]

Conclusion

Maps in Kotlin are powerful collections that allow you to store and manipulate key-value pairs efficiently. Understanding how to use both mutable and immutable maps is essential for effective data handling in Kotlin programming.