

There are various ways to loop through a Kotlin Maps.

Kotlin map has properties to get all entries, keys, and values of the map. We can use Pair() method to create key/value pairs: Example When you run the above Kotlin program, it will generate the following output:Ī Kotlin map can be created from Java's HashMap. Val theMutableMap = mutableSetOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) Val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) A read-only view of a mutable map can be obtained by casting it to Map. Creating Kotlin Mapsįor map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for mutable maps. Maps are also known as dictionaries or associative arrays in other programming languages. We can declare the keys and values to be any type there are no restrictions.Ī Kotlin map can be either mutable ( mutableMapOf) or read-only ( mapOf). The same value can be associated with multiple keys though. Now let’s see how our test would look like.Kotlin map is a collection of key/value pairs, where each key is unique, and it can only be associated with one value. Our domain objects would be the following classes then.ĭata class Customer(val name: String, val address: Address?) Therefore we’d like to update in our database just those customers with an existing address.

We also know that the address has been optional for many years, so not all of our customers have an address. The requirement is to update the address to a new format where each field is contained in a different field. For instance, we could have an address like this "22 Baker Street - W1U8ED England". `should add 1 to each element in the list`() “. This method applies a function to each element contained in a collection, creating a new collection with the new elements as a result. The most common way of transforming elements in a collection is by using map method. Photo by SOULSANA on Unsplash Regular Kotlin map method
