โ† Back to list

Convert Lists to Maps Like a Pro! ๐Ÿš€

Working with collections in Kotlin? Ever needed to quickly transform a List into a Map? Meet associateByโ€”a powerful function that allowsโ€ฆ

KrupalBhuva ยท 2025-03-01 11:27 ยท 50 claps ยท 2.4 min read
#kotlin #android-app-development #advanced-programming #prodev #interview
Open on Medium โ†—
Wiki topics: ๐Ÿ’ป ยท Programming ๐Ÿ“ฑ ยท Mobile Development ๐Ÿ”’ ยท Cybersecurity

Convert Lists to Maps Like a Pro! ๐Ÿš€

Working with collections in Kotlin? Ever needed to quickly transform a List into a Map? Meet associateByโ€”a powerful function that allows you to generate maps from lists effortlessly! Let's dive into how, when, and why to use it with unique examples! ๐Ÿ”ฅ

๐Ÿ” What is associateBy?

associateBy is a Kotlin function that transforms a List into a Map by extracting a key from each element. The original list elements remain as values.

โœ… Syntax:

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

๐Ÿ“Œ Key Points: โœ” keySelector: A lambda function that returns a unique key for each element. โœ” Returns a Map where the key is derived from the list elements, and the value is the original element.

๐Ÿš€ Why Use associateBy?

โœ” Fast Lookup: Convert lists into maps for quick element access by a key. โœ” Readable Code: More concise and declarative than traditional loops. โœ” Flexible Key Mapping: Extract keys from any property of the objects. โœ” Transform Values: Modify values during conversion with an additional lambda.

๐Ÿ”ฅ associateBy in Action

Letโ€™s explore different ways to use associateBy effectively.

1๏ธโƒฃ Convert a List of Objects to a Map by ID

Imagine we have a list of Person objects. We want to create a Map where the id is the key and the Person object is the value.

data class Person(val id: Int, val name: String)
val people = listOf(
    Person(1, "Alice"),
    Person(2, "Bob"),
    Person(3, "Charlie")
)
val peopleMap = people.associateBy { it.id }
println(peopleMap)

โœ… Output:

{1=Person(id=1, name=Alice), 2=Person(id=2, name=Bob), 3=Person(id=3, name=Charlie)}

Key Takeaways: โœ” The keys are id values (1, 2, 3). โœ” The values are Person objects.

2๏ธโƒฃ Use a Different Property as Key

Instead of using id, letโ€™s use name as the key!

val peopleMapByName = people.associateBy { it.name }
println(peopleMapByName)

โœ… Output:

{Alice=Person(id=1, name=Alice), Bob=Person(id=2, name=Bob), Charlie=Person(id=3, name=Charlie)}

Key Takeaways: โœ” The keys are names (โ€œAliceโ€, โ€œBobโ€, โ€œCharlieโ€). โœ” The values are Person objects.

3๏ธโƒฃ Modify the Values While Mapping

We can also change the values while mapping. Here, we create a map where the key is id and the value is only name.

val peopleMapById = people.associateBy({ it.id }, { it.name })
println(peopleMapById)

โœ… Output:

{1=Alice, 2=Bob, 3=Charlie}

Key Takeaways: โœ” The keys are id values (1, 2, 3). โœ” The values are only names (โ€œAliceโ€, โ€œBobโ€, โ€œCharlieโ€).

๐Ÿ›‘ Things to Watch Out For

โš ๏ธ Duplicate Keys: If multiple elements have the same key, only the last one is kept. Example:

val numbers = listOf(1, 2, 3, 2, 1)
val uniqueMap = numbers.associateBy { it }
println(uniqueMap) // {1=1, 2=2, 3=3}

๐Ÿ”น Only the last occurrence of each key remains!

โš ๏ธ Key Must Be Unique: If your key function produces duplicates unexpectedly, you might lose data!

๐ŸŽฏ When to Use associateBy

โœ” When you need quick lookups by a specific property. โœ” When you want to convert a list to a map with minimal effort. โœ” When you need to filter or transform elements during conversion.

๐Ÿ”ฅ Final Thoughts

associateBy is a game-changer for handling collections in Kotlin! ๐Ÿš€ It makes your code more readable, efficient, and expressive. Mastering this function will level up your Kotlin skills and make working with lists a breeze! ๐Ÿ˜Ž

๐Ÿ’ก Try it out and make your Kotlin code smarter today! ๐Ÿ’ช

๐Ÿ“Œ Did this help? Share with fellow devs & boost your Kotlin knowledge! ๐Ÿš€

Kotlin #AndroidDev #KotlinTips #CleanCode #CodingBestPractices #DevTips


๋ฉ”ํƒ€๋ฐ์ดํ„ฐ
post_id
cb7d2ea39ee4
slug
convert-lists-to-maps-like-a-pro-cb7d2ea39ee4
url
https://medium.com/@bhuvakrupal01/convert-lists-to-maps-like-a-pro-cb7d2ea39ee4
canonical_url
https://medium.com/@bhuvakrupal01/convert-lists-to-maps-like-a-pro-cb7d2ea39ee4
author_url
https://medium.com/@bhuvakrupal01
status
ok
fetched_at
2026-07-20 19:44:56