Introduction:- In the last post of this series, I discussed the Kotlin Collection API. In this post, I wil share how the Map APIs work.
Map
The mapping transformation creates a new collection from another collection. lambda function is applied to each subsequent element and returns the list of the lambda results. The order of results is the same.
Listing 1
val numbers = setOf(4, 5, 6)
println(numbers.map { it * 4 })
output [16, 20, 24]
. mapIndexed() should be used for element index
listing 2
val numbers = setOf(4, 5, 6)
println(numbers.mapIndexed { idx, value -> value * idx })
output
[0, 5, 12]
Listing 3 filter out the nulls from the result collection by calling the mapNotNull().
Listing 3
val numbers = setOf(4, 5, 6 )
println(numbers.mapNotNull { if ( it == 5) null else it * 4 })
output
[16, 24]
Listing 4 applies on IndexedNotNull
val numbers = setOf(4, 5, 6 )
println(numbers.mapIndexedNotNull { idx, value -> if (idx == 0) null else value * idx })
output
[5, 12]
Listing 5 shows that transformation can also be applied on keys, use mapKeys(); and , mapValues() transforms values.
Listing 5
val numbersMap = mapOf("key11" to 11, "key22" to 22, "key33" to 33)
println(numbersMap.mapKeys { it.key.uppercase() })
println(numbersMap.mapValues { it.value + it.key.length })
output
{KEY11=11, KEY22=22, KEY33=33}
{key11=16, key22=27, key33=38}
Conclusion You can see how this Map works. In the next post, I will explore the zip APIs.