Sling Academy
Home/Kotlin/Understanding Maps in Kotlin: Key-Value Pairs

Understanding Maps in Kotlin: Key-Value Pairs

Last updated: November 30, 2024

In Kotlin, maps are collections that hold pairs of objects, where one object typically serves as the key (think of it as an index) and another serves as the value (the data). Maps are essentially associative arrays, allowing you to retrieve values based on their corresponding keys.

Creating Maps in Kotlin

Kotlin provides simple ways to create maps. The most common way is using the mapOf function, which creates a read-only map:

val map: Map<String, Int> = mapOf("apple" to 1, "orange" to 2, "banana" to 3)

Here, map is a read-only map of string keys and integer values.

Mutable Maps

If you need to create a map that allows modification (adding, updating, and removing entries), you can use mutableMapOf:

val mutableMap: MutableMap<String, Int> = mutableMapOf("apple" to 1, "orange" to 2, "banana" to 3)
mutableMap["cherry"] = 4 // Adding a new entry
mutableMap["apple"] = 10 // Updating an existing entry

This creates a map that can be changed during the execution of the program.

Accessing Map Values

You can access values using the key. If you try to access a key that doesn’t exist, you'll get a null or may specify a default value:

println(mutableMap["banana"]) // Prints: 3
println(mutableMap["pineapple"]) // Prints: null
println(mutableMap.getOrDefault("pineapple", 0)) // Prints: 0

Iterating Over Maps

Maps can be iterated over in various ways. You can loop through map entries, keys, or values:

// Iterating through entries
for ((key, value) in mutableMap) {
    println("$key = $value")
}

// Iterating through keys
for (key in mutableMap.keys) {
    println("Key: $key")
}

// Iterating through values
for (value in mutableMap.values) {
    println("Value: $value")
}

Removing Entries

An entry can be removed using the remove() function. It removes the entry with the specified key if it exists:

mutableMap.remove("apple") // Removes the "apple" entry

Post this operation, the key-value pair with the key "apple" will no longer exist in the map.

Conclusion

Maps in Kotlin are a powerful and flexible way to handle key-value pairs. With both immutable and mutable options, Kotlin maps cater to various use cases—from a static map for reading to a dynamic one for manipulation during runtime. Understanding how to effectively use maps will significantly enhance your ability to manage collections of data in Kotlin.

Next Article: Creating Maps with `mapOf` and `mutableMapOf` in Kotlin

Previous Article: Iterating Over Set Elements in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin