AssociateBy - List to Map in Kotlin

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
AssociateBy - List to Map in Kotlin

I am Amit Shekhar, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Join my program and get high paying tech job: amitshekhar.me

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

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

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.

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.