What is "associate()" method in Kotlin?

Kotlin is a modern and expressive programming language that is widely known for its simple syntax and powerful features. It is used for Android app development and many Java Virtual Machine (JVM) apps.

The associate() method

The associate() function creates a new map from the items of an existing collection. It allows the transformation of collection items and utilizes them as keys and values in a new map. It handles the map creation efficiently by iterating over the collection only once.

Syntax

Here is the syntax of the associate() method:

fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>
Syntax for associate() method
  • T shows the type of elements in the collection.

  • K shows the type of keys in the resulting map.

  • V shows the type of values in the resulting map.

  • transform represents a lambda function that takes an element of type T and returns a Pair<K, V>.

Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.

Code

Let’s look at a simple code example to implement the associate() method.

Suppose we have a list of countries and their respective capitals. We want to make a map where the nation is the key, and the capital represents the value.

fun main() {
val countries = listOf("USA", "France", "Japan")
val capitals = listOf("Washington D.C.", "Paris", "Tokyo")
val countryToCapitalMap = countries.associate { country ->
country to capitals[countries.indexOf(country)]
}
println(countryToCapitalMap)
}

Code explanation

  • Line 1–3: Firstly, we define two lists: countries that have three items and capitals with three items.

  • Line 5: Next, we use the associate() method on the countries list to create a map.

  • Line 6: Here, we use the lambda function to transform each country into a pair of the country and its corresponding capital.

  • Line 9: Finally, we print the resulting map that maps countries to their capitals.

Output

Upon execution, the code will create a map where each country is associated with its respective capital. The lambda function assures that the correct capital is paired with each country based on their positions in the lists.

The output looks something like this:

{USA=Washington D.C., France=Paris, Japan=Tokyo}

Conclusion

Therefore, Kotlin's associate() function is a powerful tool that optimizes the process of building maps from collections. It can efficiently convert items and form key-value pairs, resulting in cleaner and more maintainable code. It provides a simple and fast mechanism to make such transformations in the code.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved