AssociateBy - List to Map in Kotlin

amitiitbhu

Amit Shekhar

Posted on September 17, 2022

AssociateBy - List to Map in Kotlin

Hi, I am Amit Shekhar, Co-Founder @ Outcome School • IIT 2010-14 • 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.

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 Outcome School.

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)
Enter fullscreen mode Exit fullscreen mode

And, a list of Contact:

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

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)
Enter fullscreen mode Exit fullscreen mode

This will print the following:

{Amit=+9199XXX11111,
Messi=+9199XXX22222,
Ronaldo=+9199XXX33333}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

Co-Founder @ Outcome School

You can connect with me on:

Read all of our blogs here.

💖 💪 🙅 🚩
amitiitbhu
Amit Shekhar

Posted on September 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related