Transforming data is a common requirement for most modern Android applications. Kotlin helps out by providing functions in the standard library for transforming your collection data. In this video, take a look at the map and groupBy functions.
- [Instructor] Transforming data is a common requirement for most modern Android apps. Kotlin helps us out by providing functions in the standard library for transforming our collection data. Let's say we have a list of users, but we actually need a list of their names. One approach could be to create a new list, then iterate over the existing list and add the users' names. But Kotlin offers us a better way. We can use the map function and provide a lambda, which contains the transformation that we're interested in.
Notice that we're using our familiar it variable. This represents a given instance of a user, and then we simply grab their name. This results in a new list, which contains the name of each user. We can even rewrite this using member references and get the same result. Another useful function for mapping your data is the groupBy function. Let's say you have a list of users and you want to divide them into groups based on whether or not they can legally drive.
Using the groupBy function, we will provide a lambda with our separation criteria. In this case, if the person's age is 16 or greater, we add them to the legal group. Otherwise, they get put in the illegal group. The result is a map with string keys and a list of users for the values. And of course if you like, you could take that list and then do further modifications on it. The general rule of thumb is to look for a library function to help you out when you need to transform your data in your Kotlin collections.
- What Kotlin has to offer
- Working with lambdas
- Common Android extension functions
- Kotlin Android Extensions overview
- Making use of the Anko library
- Working with coroutines
- Nullability and collections