A map stores associations between unique keys and values. Use it for direct lookup, updating values by key, grouping collection elements, or transforming a collection into an associative structure. section 2.4.3 section 6.1.5
Listing 2.25 Initializing and iterating over a map
fun main() {
val binaryReps = mutableMapOf<Char, String>() #1
for (char in 'A'..'F') { #2
val binary = char.code.toString(radix = 2) #3
binaryReps[char] = binary #4
}
for ((letter, binary) in binaryReps) { #5
println("$letter = $binary")
}
// A = 1000001 D = 1000100
// B = 1000010 E = 1000101
// C = 1000011 F = 1000110
// (output split into columns for conciseness)
}
Builds a mutable map from characters to binary strings, updates it with bracket syntax, and iterates through unpacked key-value pairs. section 2.4.3
The example uses `mutableMapOf<Char, String>()` because it adds entries during the loop. `binaryReps[char] = binary` updates a value without the Java-style `put` call, while `for ((letter, binary) in binaryReps)` destructures each key-value pair. section 2.4.3
Collection transformations produce maps in different ways:
- `groupBy` uses a property such as age or first character as the key and stores matching elements in lists. section 6.1.5
- `associate` transforms each element into a key-value pair, such as a person's name and age. section 6.1.6
- `associateWith` keeps collection elements as keys; `associateBy` keeps them as values and generates the keys. section 6.1.6
- Generated keys must be unique; a later value overwrites an earlier value when transformations produce the same key. section 6.1.6
Grouping people by age
`people.groupBy { it.age }` produces a `Map<Int, List<Person>>`, such as age 31 mapped to Alice and Carol, and age 29 mapped to Bob. section 6.1.5









































