Kotlin List.associate()
The Kotlin List.associate() function is used to create a map where the keys and values are derived from the elements of a collection.
The function takes a lambda expression that defines how to extract the key-value pairs from the elements of the collection.
Syntax
List.associate(transform: (T) -> Pair<K, V>)
The function returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.
Example 1: Create a Map from List of user defined objects
In this example, we take a list of user defined objects, and create a Map from this list.
- Take a list of objects in
persons
, where each object is of typePerson(id, name, age)
. - We have to convert this list of
Person
objects into a map, where theid
property is used for the key, and thename
property is used for value. - Call associate() function on persons list, and pass a transform (lambda expression) that maps the
id
property to thename
property. - You may print the returned map idToNameMap to output.
Program
data class Person(val id: Int, val name: String, val age: Int)
fun main() {
val persons = listOf(
Person(1, "Alice", 24),
Person(2, "Bob", 27),
Person(3, "Charlie", 31)
)
val idToNameMap: Map<Int, String> = persons.associate { person -> person.id to person.name }
println(idToNameMap)
}
Output
{1=Alice, 2=Bob, 3=Charlie}
The List.associate()
function is a convenient way to transform elements of a collection into a map, and it’s particularly useful when you have a collection of objects and want to create a mapping based on some properties of those objects.
Example 2: Create a Map from List of integers
In this example, we take a list of integer values, and associate these integer values with their respective ASCII character values. The integer value shall be the key, and the ASCII character shall be the value.
- Take a list of integers in charCodes. This is an integer list containing ASCII integer values of some of the alphabets.
- Call associate() function on charCodes list, and pass a transform that maps the integer value in the list to respective Char. Store the returned map in byCharCode.
- You may print the returned map byCharCode to output.
Program
fun main() {
val charCodes = intArrayOf(72, 69, 76, 76, 79)
val byCharCode = charCodes.associate { it to Char(it) }
println(byCharCode)
}
Output
{72=H, 69=E, 76=L, 79=O}
If you observe the output, and relate it to the input, we can make the following points.
- The iteration order of the original list is preserved in the map.
- Since the map contains only unique keys, only one entry with key value of
76
is present in the returned map.