![]() |
VOOZH | about |
In Kotlin, a Map is a collection that stores data in key-value pairs. Each key in a map is unique, and the map holds only one value for each key. If a key is repeated, only the last value is retained.
Kotlin distinguishes between:
Syntax:
fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V>If multiple entries use the same key, only the last value is kept.
Example of mapOf() -
Output:
{1=Geeks, 2=for, 3=Geeks}Output:
Map Entries : {1=One, 2=Two, 3=Three, 4=Four}
Map Keys: [1, 2, 3, 4]
Map Values: [One, Two, Three, Four]
We can determine the size of map using two methods. By using the size property of the map and by using the count() method.
Output:
The size of the map is: 4
The size of the map is: 4
We can create an empty map using mapOf() with no arguments.
Example -
Output:
Entries: []
Keys:[]
Values:[]
We can retrieve values from a map using different methods discussed in the below program.
Output:
Team having rank #1 is: India
Team having rank #3 is: England
Team having rank #4 is: Africa
Australia
We can determine that a map contains a key or value using the containsKey() and containsValue() methods respectively.
Output:
Yes, it contains color yellow
No, it does not contain value 8
If two values have same key value , then the map will contain the last value of the those numbers.
Example 3: mapOf()
Output:
Entries of map : [1=geeks2, 2=for]Explanation:
Here key value 1 has been initialized with two values: geeks1 and geeks2, but as we know that mapOf()can have only one value for one key item, therefore the last value is only stored by the map, and geeks1 is eliminated.
Output:
Names: {John=25, Mary=30, Bob=20}
Contains Mary: true
In this example, we create a new read-only map of strings using the mapOf() function with the key-value pairs "John" to 25, "Mary" to 30, and "Bob" to 20. We then retrieve the value associated with the key "John" using the square bracket notation and store it in the variable johnAge. Finally, we check if the map contains the key "Mary" using the containsKey() function and print the result to the console.