Amit Shekhar
Posted on September 17, 2022
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)
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.
That's it for now.
Thanks
Amit Shekhar
Co-Founder @ Outcome School
You can connect with me on:
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
November 21, 2024