Kotlin Map

Learn via video courses
Topics Covered

Overview

Map in Kotlin are essential collections for storing unique key-value pairs. Kotlin provides both mutable mutableMapOf() and immutable mapOf() map implementations. Immutable maps cannot be modified after creation, while mutable maps allow dynamic updates. They offer efficient data retrieval, insertion, deletion, and key-value pair management, enhancing code readability. These key-value pairs are often referred to as 'entries' following the Entry interface.

In computer science, maps are versatile data structures that Kotlin leverages extensively, and they are commonly known as dictionaries or associative arrays in other languages.

Syntax

  • The mapOf() function constructs a map in Kotlin.
  • It accepts pairs of key-value elements as its parameters.
  • Each pair consists of two values; the first value is the key, and the second value is the corresponding value for that key.
  • The function creates a map where keys are associated with their respective values.
  • The order of insertion is preserved in the resulting map.
  • This function is useful for quickly creating and initializing maps with predefined values.

Kotlin Program of Mapof()

  • We establish a map named countryToCapital using the mapOf() function.
  • This map is designed to link countries with their corresponding capital cities.
  • We showcase how to retrieve capital cities by using country names as unique keys.
  • The map is traversed using a loop to display each country and its associated capital.
  • This example underlines the flexibility of the mapOf() function in constructing maps to manage various kinds of data associations.

Map Keys, Values and Entries

  • Keys: Keys in a map are unique identifiers that are used to associate values. Each key corresponds to a specific value within the map. Keys serve as labels or references that allow efficient retrieval of associated data.
  • Values: Values are the data elements associated with keys in a map. They represent the actual information or content that you want to store, retrieve, or manipulate. Each key is associated with a single value in the map.
  • Entries: An entry in a map represents a key-value pair. It encapsulates both the key and its corresponding value. Entries collectively make up the content of the map. When you iterate over a map, you're essentially iterating over its entries, accessing both the keys and values.

Example

Output

Explanation

  • Keys: Student names like "Alice," "Bob," and "Charlie" serve as unique identifiers.
  • Values: The values are the scores associated with each student.For instance,95 for "Alice," 85 for "Bob," and 78 for "Charlie."
  • Entries: An entry in the map consists of a key-value pair.For instance,"Alice" paired with 95, linking names and scores.
  • The scores of "Alice" and "Charlie" are directly accessed using their keys, and their respective scores are printed.
  • The loop iterates through the map's entries, printing each student's name and their associated score.

Map Size

The size of a map in Kotlin corresponds to the quantity of key-value pairs or entries it holds. In Kotlin, you can retrieve the map's size using the size property. This property offers the total count of elements (entries) contained within the map.

Example

Output

Empty Map

An empty map in Kotlin is a map that contains no key-value pairs or entries. It essentially has zero elements. In Kotlin, you can create an empty map using the emptyMap() function.

Example

Output

Explanation In this example, the emptyMap has been created using the emptyMap() function. The size property is then used to retrieve and print the size of the empty map, which is 0 since it doesn't contain any elements.

Get values of Map

There are four common methods to retrieve values from a map in Kotlin:

  1. Using Indexing (Keys): The simplest approach involves using keys as indexes to retrieve values from the map in kotlin. When the key is present, it yields the associated value; otherwise, it returns null.
  2. Using the get() Function: The get() function can be used to retrieve the value associated with a specified key. It behaves similarly to indexing.
  3. Using the getOrElse() Function: The getOrElse() function allows you to provide a default value that will be returned if the key is not found in the map.
  4. Using the getOrDefault() Function: The getOrDefault() function is similar to getOrElse(), but it provides a simpler way to specify a default value directly.

Example

Output

Map Contains Key or Values

You can check if a map in kotlin contains a specific key or value using the containsKey() and containsValue() functions, respectively. These functions return true if the key or value is found in the map, and false otherwise. Here's an example demonstrating both functions:

Output

Explanation

  • We have a map animalSounds that associates animal names with their corresponding sounds.
  • containsKey() is used to check whether specific keys ("Dog" and "Elephant") are present in the map. hasDog is true because "Dog" is a key, while hasElephant is false because "Elephant" is not a key.
  • containsValue() is used to check whether specific values ("Meow" and "Quack") are present in the map. hasMeow is true because "Meow" is a value, while hasQuack is false because "Quack" is not a value.

Two Values and Same Key

If you add two values with the same key to a map, the map will retain only the latest value, replacing any previous value associated with that key. This ensures uniqueness for each key and its corresponding single value in the map. Example

Output:

Explanation:

  • We create a mutable map studentAges that associates student names with their ages.
  • After creating the map, we use the indexing syntax ([]) to update the age of "Alice" from 20 to 23.
  • When we print the map, we can see that the value for the key "Alice" has been updated to 23.

Using mapOf() to create a map of strings

Lets see an example that uses the mapOf() function to create a map of strings, where the keys represent days of the week and the values represent corresponding activities:

Output

Explanation

  • We use the mapOf() function to create a map named dayActivities that associates days of the week with their corresponding activities.
  • The keys are strings representing the days of the week , and the values are strings representing activities associated with those days ("Work", "Gym", etc.).
  • We access and print the values from the map using the keys, showcasing how the map links days to activities.

Advantages of mapOf()

  • Simplicity: Creating a map is straightforward and concise, aiding in defining key-value pairs.
  • Read-Only: The map is read-only, ensuring data integrity and avoiding accidental changes.
  • Immutable: Key-value pairs remain unalterable, ensuring consistent data and minimizing unintended modifications.

Disadvantages of mapOf()

  • Limited Mutability: Cannot modify map after creation, restricting dynamic updates.
  • Performance Overhead: Recreating map for changes can impact efficiency with large datasets.
  • Flexibility Constraints: Inflexible for adding or removing entries compared to other map types.
  • No Default Values: Lack of built-in support for specifying default values or custom handling for missing keys.

Conclusion

  1. Kotlin's mapOf() function eases map creation by allowing convenient definition of key-value pairs.
  2. Maps consist of unique keys linked to specific values, forming entries that make up the map's content.
  3. The size property quickly determines map size, while getValue(), containsKey(), and containsValue() functions assist in data retrieval and validation.
  4. Maps retain the latest value when two values with the same key are added, ensuring each key remains unique.
  5. Kotlin's mapOf() simplifies map creation, providing organized data structures; however, its immutability might limit dynamic changes in certain scenarios