- The map is an interface and a collection in Kotlin.
- Maps are used to hold the pairs of objects in the form of a key/value.
- The keys are unique in a map while for each key there can be one value.
- Kotlin map supports efficiently retrieving the value for the corresponding key.
- The map is an immutable collection, so its methods only support the read-only access to the map.
- To create a mutable map with read-write methods, you may use the MutableMap interface.
- You may use different functions like mapOf(), mutableMapOf(), etc. for creating a map in Kotlin.
How to create a map and access items?
In the first example, we will create a map with keys of int type and values of strings.
For creating a map, you may use the mapOf() function.
This is followed by using a for loop to access the map elements. In the for loop body, we will display the keys and corresponding values:
fun main(args: Array<String>) { val emp_map = mapOf<String, String>("Name" to "Mike", "Age" to "40", "Salary" to "$5000") for ((k, v) in emp_map) { println("$k = $v") } }
The result of the above code:
Name = Mike
Age = 40
Salary = $5000
You can see how we used the key and value in the for loop and how the name of map is given. The mapOf() function creates the immutable map.
Accessing a specific element by getValue() function
The getValue() function returns the value of the property for the given object.
In the case of a map, it returns the value for the given key as follows:
fun main(args: Array<String>) { val emp_map = mapOf<String, String>("Name" to "Mike", "Age" to "40", "Salary" to "$5000") println("The age of employee is " +emp_map.getValue("Age")) }
The result:
Using keys property example
The “keys” is a property of the map interface that returns a read-only set of all the key/value pairs in the set.
See what it returns for our above created map:
fun main(args: Array<String>) { val emp_map = mapOf<String, String>("Name" to "Shella", "Age" to "25", "Salary" to "$2250") println("The keys in the map are: " +emp_map.keys) }
The output:
Getting the size of a map example
The size property returns the total number of key/value pairs in the map. The example below shows how to use it:
fun main(args: Array<String>) { val emp_map = mapOf<String, String>("Name" to "Areeb", "Age" to "33", "Salary" to "$4550") println("The size of map is: " +emp_map.size) }
The output:
The example of using values property
The values property returns a collection of read-only values in this map.
The returned collection may contain duplicate values. See an example below:
fun main(args: Array<String>) { val emp_map = mapOf<String, String>("Name" to "Holder", "Age" to "32", "Salary" to "$3300") println("The values in map: " +emp_map.values) }
The output: