https://grokonez.com/kotlin/kotlin-map-collection-map-methods
Kotlin Map collection – map() methods
In the tutorial, JavaSampleApproach will show you how to use map()
methods to transform Kotlin Map collection to Kotlin List collection or a new Map collection.
I. Kotlin Map collection with map() methods
Kotlin Map collection supports a set of map() methods to transform the given map to a new map or a new list:
1. fun <K, V, R> Map<out K, V>.map(transform: (Map.Entry<K, V>) -> R): List<R>
2. fun <K, V, R : Any> Map<out K, V>.mapNotNull(transform: (Map.Entry<K, V>) -> R?): List<R>
3. fun <K, V, R, C : MutableCollection<in R>> Map<out K, V>.mapTo(destination: C, transform: (Map.Entry<K, V>) -> R): C
4. fun <K, V, R : Any, C : MutableCollection<in R>> Map<out K, V>.mapNotNullTo(destination: C, transform: (Map.Entry<K, V>) -> R?): C
5. fun <K, V, R> Map<out K, V>.mapKeys(transform: (Map.Entry<K, V>) -> R): Map<R, V>
6. fun <K, V, R> Map<out K, V>.mapKeys(transform: (Map.Entry<K, V>) -> R): Map<R, V>
7. fun <K, V, R> Map<out K, V>.mapValues(transform: (Map.Entry<K, V>) -> R): Map<K, R>
8. fun <K, V, R, M : MutableMap<in K, in R>> Map<out K, V>.mapValuesTo(destination: M, transform: (Map.Entry<K, V>) -> R): M
Now practicing ->
0. Initial data for practicing
data class Address(
val street: String,
val postcode: String
)
data class Customer(
val firstName: String,
val lastName: String,
val age: Int
)
data class Person(
val fullname: String,
val age: Int,
val address: Address
)
val customerMap = mapOf(Pair(Customer("Jack", "Davis", 25), Address("NANTERRE CT", "77471")),
Pair(Customer("Mary", "Taylor", 37), Address("W NORMA ST", "77009")),
Pair(Customer("Peter", "Thomas",17), Address("S NUGENT AVE", "77571")),
Pair(Customer("Amos", "Nelson",23), Address("E NAVAHO TRL", "77449")),
Pair(Customer("Craig", "White",45), Address("AVE N", "77587")),
Pair(Customer("Laura", "Lewis", 32), Address("NANTERRE CT", "77471")),
Pair(Customer("Steven", "Harris", 39), Address("S NUGENT AVE", "77571")),
Pair(Customer("Paul", "Moore", 18), Address("E NAVAHO TRL", "77449")),
Pair(Customer("Mary", "Cook", 61), Address("S NUGENT AVE", "77571")),
Pair(null, null))
1. Transform a given Kotlin Map to List
1.1 map()
Method signature:
More at:
https://grokonez.com/kotlin/kotlin-map-collection-map-methods
Kotlin Map collection – map() methods
Top comments (0)