AssociateBy - List to Map in Kotlin

AssociateBy - List to Map in Kotlin

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about the Kotlin Collection Functions - associateBy that converts a list into a map.

This article was originally published at amitshekhar.me.

There are many useful collection functions in Kotlin. It is good to know about those and use those based on the requirement. One of those collection functions is associateBy.

associateBy let us convert a list into a map.

Let's learn by example.

Consider a data class Contact like below:

data class Contact(val name: String, val phoneNumber: String)

And, a list of Contact:

val contacts = listOf(
    Contact("Amit", "+9199XXX11111"),
    Contact("Messi", "+9199XXX22222"),
    Contact("Ronaldo", "+9199XXX33333"))

Now, let's use the associateBy function on this list of Contact to get a Map with the

  • key as name
  • value as phoneNumber
val nameToNumberMap = contacts.associateBy( {it.name}, {it.phoneNumber})
println(nameToNumberMap)

This will print the following:

{Amit=+9199XXX11111,
Messi=+9199XXX22222,
Ronaldo=+9199XXX33333}

If we go through the source code, we will find the following definition:

inline fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V>

Note:

  • Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.
  • If any two elements is having the same key returned by keySelector then, the last one will get added to the map.
  • Maintain the original order of items.

That's it for now.

Thanks

Amit Shekhar

You can connect with me on: