![]() |
VOOZH | about |
In Kotlin, mutableMapOf() is used to create a MutableMap. A MutableMap holds key-value pairs where keys are unique, but values can be duplicated. This means that each key points to exactly one value, but two or more keys can point to the same value.
For example, we can create maps like:
1. To create an empty MutableMap:
val map = mutableMapOf<K, V>()This creates an empty MutableMap.
2. To create a MutableMap with key-value pairs:
val map = mutableMapOf(key1 to value1, key2 to value2)Output:
Entries: {Box=12, Books=18, Table=13}
Keys: [Box, Books, Table]
Values: [12, 18, 13]
We can determine the size of mutable map using two methods. By using the size property of the map and by using the count() method.
Example:
Output:
Size using size property: 4
Size using count() method: 4
We can retrieve values from a mutable map using different methods discussed in the below program.
Example:
Output:
Team ranked #1 is: India
Team ranked #3 is: England
Team ranked #4 is: Africa
Australia
The put() and putAll() function is used to add elements in the MutableMap.put() function adds single element at time while putAll() function can be used to add multiple element at a time in MutableMap.
Example:
Output:
<----Traverse mutableMap---->
Key = Name, Value = Geek
Key = Country, Value = India
<----Traversal after putAll()---->
Key = Name, Value = Geek
Key = Country, Value = India
Key = Department, Value = Computer Science
Key = Hobby, Value = Coding
Following methods are used to remove an element from a mutable map:
Example:
Output:
Key = Name, Value = Geek
Key = Company, Value = GeeksforGeeks
Key = Country, Value = India
Removing 'Country' key...
Was the pair removed?: true
<---Traverse Again--->
Key = Name, Value = Geek
We can remove all entries from the map using the clear() function.
Example:
Output:
Key = Name, Value = Geek
Key = Company, Value = GeeksforGeeks
Map after clear(): {}
We can traverse (loop through) a MutableMap by using a for loop and entry set.
Example:
Output:
Key = 1, Value = Aditya
Key = 4, Value = Vilas
Key = 2, Value = Manish
Key = 3, Value = Manjot