0
0
Kotlinprogramming~10 mins

Map transformation in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Map transformation
Start with original Map
Apply transformation function
Create new Map with transformed entries
Return new transformed Map
We start with an original map, apply a function to each entry, and build a new map with the transformed keys and/or values.
Execution Sample
Kotlin
val original = mapOf("a" to 1, "b" to 2)
val transformed = original.mapValues { it.value * 10 }
println(transformed)
This code multiplies each value in the map by 10 and prints the new map.
Execution Table
StepEntry (key to value)Transformation AppliedResulting EntryNew Map State
1"a" to 11 * 10"a" to 10{"a"=10}
2"b" to 22 * 10"b" to 20{"a"=10, "b"=20}
3All entries processed--Final map: {"a"=10, "b"=20}
💡 All entries processed, transformation complete.
Variable Tracker
VariableStartAfter 1After 2Final
original{"a"=1, "b"=2}{"a"=1, "b"=2}{"a"=1, "b"=2}{"a"=1, "b"=2}
transformed{}{"a"=10}{"a"=10, "b"=20}{"a"=10, "b"=20}
Key Moments - 2 Insights
Why does the original map not change after transformation?
Because mapValues creates a new map with transformed values without modifying the original map, as shown in execution_table rows 1 and 2 where 'original' stays the same.
What does 'it.value * 10' mean in the transformation?
'it' refers to each map entry, and 'it.value' accesses the value part. Multiplying by 10 changes the value while keeping the key same, as seen in the transformation applied column.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the new map state after processing the first entry?
A{"a"=1, "b"=2}
B{"b"=20}
C{"a"=10}
D{}
💡 Hint
Check the 'New Map State' column at Step 1 in the execution_table.
At which step does the transformed map contain both entries?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'New Map State' column to see when both keys appear.
If the transformation was changed to 'it.key.uppercase()', what would happen?
AKeys become uppercase, values unchanged
BNo change
CKeys and values both become uppercase
DValues become uppercase, keys unchanged
💡 Hint
mapValues only changes values, keys stay the same as shown in the example.
Concept Snapshot
Map transformation in Kotlin:
- Use mapValues or mapKeys to create a new map
- mapValues changes values, keys stay same
- mapKeys changes keys, values stay same
- Original map is not modified
- Transformation function applies to each entry
- Result is a new map with transformed entries
Full Transcript
This visual execution shows how Kotlin transforms a map using mapValues. We start with an original map with keys "a" and "b" and values 1 and 2. Each value is multiplied by 10 to create a new map. The original map remains unchanged. Step by step, the new map builds up with transformed entries. This helps beginners see how map transformations work without changing the original data.