kotlin
  1. kotlin-mutablemapof

Kotlin mutableMapOf()

In Kotlin, a mutable Map is a collection of key-value pairs where each value is identified by a unique key. The mutableMapOf() function is used to create a mutable map with the specified initial key-value pairs. In this tutorial, we'll explore how to use mutableMapOf() function in Kotlin.

Syntax

The syntax for creating a mutable map using mutableMapOf() function is as follows:

val map = mutableMapOf<Key, Value>(initialKey1 to initialValue1, initialKey2 to initialValue2, ...)

Here, Key and Value are the data types of the keys and values, respectively. initialKey1, initialValue1, initialKey2, initialValue2, etc. are the initial key-value pairs.

Example

Let's say you want to create a mutable map of type Int for keys and String for values, with the initial key-value pairs of (1, "one"), (2, "two"), (3, "three"). You can create the map using the mutableMapOf() function as follows:

val myMap = mutableMapOf<Int, String>(1 to "one", 2 to "two", 3 to "three")

Output

The output of the mutable map will be:

{1=one, 2=two, 3=three}

Explanation

In Kotlin, a mutable map is a collection of key-value pairs, where each value is uniquely identified by its key. The mutableMapOf() function is used to create a mutable map with the specified initial key-value pairs. When you create a mutable map using mutableMapOf() function, it returns an instance of MutableMap interface.

Use

You can use mutable maps to store and retrieve data based on an identifier, which could be a String, Int, or any other data type that can be used as a key. Mutable maps are useful in scenarios where you need to map a unique value to a key. For example, you can use mutable maps to store a list of items and their prices, a list of names and their corresponding addresses.

Important Points

  • The keys in a mutable map must be unique.
  • The values in a mutable map can be duplicated.
  • Mutable maps are mutable, meaning that you can add new entries, remove entries, and change the values of existing entries.

Summary

The mutableMapOf() function in Kotlin is used to create a mutable map with the specified initial key-value pairs. A mutable map is a collection of key-value pairs, and each value is uniquely identified by its key. You can use mutable maps for storing and retrieving data based on an identifier. Mutable maps are mutable, meaning that you can add new entries, remove entries, and change the values of existing entries.

Published on: