Kotlin Tip #37: Transforming Collections with map and flatMap — 100 Kotlin Tips in 100 Days

Raphael De Lio
Kotlin with Raphael De Lio
2 min readMar 18, 2024

--

Twitter | LinkedIn | YouTube | Instagram
Tip #36: Use filter and filterNot to Collection filtering

Kotlin provides elegant solutions for common programming tasks, such as transforming collections. Two functions that can be used for collection transformation are map and flatMap.

The map function applies a given transformation to each element in a collection, returning a list containing the results of these transformations. This makes map your go-to for converting elements of a collection from one form to another.

Consider a scenario where you have a list of integers and you want to square each number:

Here, map iterates over each element, applies the squaring operation, and collects the results into a new list.

While map deals with transformations that result in a one-to-one mapping from the original collection to the transformed collection, flatMap is more nuanced. It is particularly useful when each element in the original collection is transformed into a collection of items, and you want to flatten these collections into a single list.

Imagine you have a list of strings where each string contains multiple words, and you wish to obtain a list of individual words:

flatMap first maps each string to a list of words (using split in this case) and then flattens these lists into a single list of words.

Both map and flatMap are important for data transformation tasks, enabling more expressive and idiomatic Kotlin code. They not only simplify the code but also enhance its readability and maintainability. By using these functions, developers can perform complex collection transformations with minimal, straightforward code.

I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!

Stay curious!

Tip #38: Use groupBy to organize collections by criteria

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--