Sneh Pandya Exploring the horizon with a knack for product management. Co-host of the NinjaTalks podcast and community organizer at Google Developers Group. Explorer, adventurer, traveler.

A guide to using the Map interface in Kotlin

4 min read 1198

Guide To Using Map Interface In Kotlin

If you’re interested in Android app development or Kotlin multiplatform development, you may have come across the collections framework in Kotlin.

Kotlin has a comprehensive set of tools for managing collections. Collections are used extensively in most programming languages, and they are made up of pieces or items that are all of the same sort.

An understanding of the Kotlin collections framework and how to use it effectively in the development of apps will help you get a grip of this programming language and its capabilities.

In this article, you will learn about the Map interface in Kotlin as well as its usage and association with coding examples.

Collections framework in Kotlin

By making use of collections, you can store, update, retrieve, and aggregate data points. The Kotlin Standard Library provides a comprehensive set of tools for managing collections.

Collections are read-only by default in Kotlin. Instead of modifying the contents of a collection, you need to build a new collection with the modifications applied, which you can then securely move around in your application while the old collection stays unaltered.

Kotlin collections are categorized into two types:

  • Immutable collection
  • Mutable collection

The following collection types are relevant for Kotlin:

  • Kotlin List: An ordered collection with access to elements by indices. (Note: Elements can occur more than once in a list)
  • Kotlin Set: A collection of unique elements; which means a group of objects without repetitions
  • Kotlin Map: A set of key-value pairs. Keys are unique, and each of them maps to exactly one value

Apart from this, Kotlin also has mutable variants of the collection: MutableList, MutableSet, and MutableMap, which allows you to modify the collection, such as adding or removing elements.

The mutable types are extremely useful where the data needs to be manipulated frequently, as per the requirements; a good example of this can be API call results shown in the form of a list with filters or search queries.

We made a custom demo for .
No really. Click here to check it out.

Introduction to maps in Kotlin

Map is also known as dictionaries or associative arrays in other programming languages. Maps in Kotlin are immutable by default as part of the collections framework. This implies that once an element in Map is generated, it cannot be edited, removed, or updated.

However, Kotlin enables users to create changeable maps, or maps that can be changed after they’ve been created. The requirement is that, if you want to create a changing Map, you must use the changeable map type.

To use the Map interface in Kotlin, you need to use its function, called mapOf() or mapOf<k,v>().

An example of a Map object is shown here:

val peopleToCarsOwned = mapOf(
   "Jack" to "Mercedes",
   "John" to "Audi",
   "Will" to "Jaguar"
)
println(peopleToCarsOwned)

// This will print the output:
// {Jack=Mercedes, John=Audi, Will=Jaguar}

println(carsOwned["John"])
// This will print the output:
// Audi

While associating data, key-value pairs are widely used everywhere in Kotlin. Thus, Map becomes one of the go-to ways to manage structured data in Kotlin.

There are several functions that can be applied on Map to process the relevant data needed as a result. Let’s have a look at some of the common functions now.

Retrieving data

A Kotlin Map‘s ability to access key-value pairs is crucial. To obtain keys and values, use the get method. getKey is used to obtain the value of a specified key. If the key does not exist, a null value will be returned.

The getValue method returns the key associated with the value. However, if the value given in the get function has no associated key, the getValue method provides additional options.

In such cases, methods like getOrElse and getOrDefault can be used. In the event that a key cannot be found, getOrElse allows you to replace a different key. In the event that a key cannot be found, getOrDefault delivers the default key that you requested.

Filtering data

When using Map and accessing key-value pairs, filtering the data to find specific information and key-value pairs is useful. Like other collections in Kotlin, Map can be filtered with the filter function.

FilterKey and filterValue are similar to the get method, since they allow you to filter by key or value. When a filter is applied, a new Map with only the filtered elements is returned. If you use filterKey, for example, you will obtain a Map that is made up entirely of the specified keys.

Have a look at the example below:

open class Car(val name: String, val manufacturedIn: Int) {
    override fun toString() = name
}

val cars = mapOf(
    "Aston Martin" to 2015,
    "Lamborghini" to 2000,
    "BMW" to 1990,
    "Mercedes Benz" to 1980
)

val newCars = cars.filter {
    it.manufacturedIn >= 2000
}

println(newCars)
// This will return the output: [Aston Martin, Lamborghini]

If you need to negate a condition, then the filterNot function comes handy, which is used in a similar way to the filter function as below:

// Kotlin
val oldCars = cars.filterNot {
    it.age >= 2000
}

println(oldCars)
// This will return the output: [BMW, Mercedes Benz]

Editing data

Since Map is immutable by default, if you want to make modifications to a Map, you’ll need to create a changeable Map first. It’s also worth noting that keys can’t be changed, but they can be deleted — you’re modifying the value of a key when you edit an entry.

You can create new key-value combinations, update the value of an existing key, or completely eliminate a key-value combination. To add new data to your Kotlin Map, you need to use the put method.

If the key you entered already exists in your Map, however, you may use the put method to replace the existing value for that key. Using remove, you may totally delete entries from your Kotlin Map.

Working with maps in Kotlin

Have a look at the examples and scenarios below, to better understand how the Map interface in Kotlin works:

val genericMap: Map<Int, String> = mapOf<Int,String>(
    1 to "Jack",
    4 to "John",
    3 to "Will"
)

for(key in genericMap.keys) {  
    println("Element at key position $key: ${genericMap.get(key)}")
}  

// This will print the output:
// Element at key position 1: Jack
// Element at key position 4: John
// Element at key position 3: Will

If you cannot specify any type of key and value for Map, then it can accept different types of key-value pairs at once. This is possible because the Map implementation internally uses <Any, Any> declaration. Have a look at this example:

val customMap = mapOf(
    1 to "Rick",
    4 to "Tesla",
    3 to True,
    "Train" to "Station",
    "Rocket" to "Launch"
    )

for(key in customMap.keys) {  
    println("Element at key position $key: ${customMap.get(key)}")
}

// This will print the output:
// Element at key position 1: Rick
// Element at key position 4: Tesla
// Element at key position 3: True
// Element at key position Train: Station
// Element at key position Rocket: Launch

Conclusion

While an in-depth understanding of how Map interface operates in Kotlin is unlikely to be required to supercharge your app, a basic understanding of how Map works in Kotlin is essential.

Such data structures enable many of the functionalities that users have grown to expect from modern mobile applications.

Sneh Pandya Exploring the horizon with a knack for product management. Co-host of the NinjaTalks podcast and community organizer at Google Developers Group. Explorer, adventurer, traveler.

Leave a Reply