AssociateBy - List to Map in Kotlin
- Authors
- Name
- Amit Shekhar
- Published on
I am Amit Shekhar, Co-Founder @ Outcome School, 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 Outcome School and get high paying tech job: Outcome School
Before we begin, we’d like to mention that we’ve launched our YouTube channel. Subscribe to the Outcome School YouTube Channel.
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
asname
value
asphoneNumber
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 byvalueTransform
and indexed bykeySelector
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
Co-Founder @ Outcome School
You can connect with me on:
Follow Outcome School on: