The Kotlin map collection

  • The map is an interface and a collection in Kotlin.
  • Maps are used to hold the pairs of objects in the form of 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.
  • For creating 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 of key 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 for accessing the map elements. In the for loop body, we will display the keys and corresponding values:

The result of 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 value for the given key as follows:

The result:

The age of employee is 40

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 out above created map:

The output:

The keys in map are: [Name, Age, Salary]

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:

The output:

The size of map is: 3

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:

The output:

The values in map: [Holder, 32, $3300]