🗺️ Map (Dictionary)
🎯 Mục tiêu: Nắm vững Map - collection lưu trữ cặp key-value, giống dictionary trong các ngôn ngữ khác.
💡 Khái niệm
Phần tiêu đề “💡 Khái niệm”Map lưu trữ các cặp key-value. Mỗi key là unique.
val capitals = mapOf( "Vietnam" to "Hanoi", "Japan" to "Tokyo", "France" to "Paris")println(capitals["Vietnam"]) // Hanoi📝 Tạo Map
Phần tiêu đề “📝 Tạo Map”// Immutableval map = mapOf("a" to 1, "b" to 2)val empty = emptyMap<String, Int>()
// Mutableval mutableMap = mutableMapOf("a" to 1)val hashMap = hashMapOf("a" to 1)val linkedMap = linkedMapOf("a" to 1) // Giữ thứ tựval sortedMap = sortedMapOf("b" to 2, "a" to 1) // Sort by key🔍 Truy cập
Phần tiêu đề “🔍 Truy cập”val scores = mapOf("Alice" to 95, "Bob" to 87, "Charlie" to 92)
// Getprintln(scores["Alice"]) // 95println(scores["Unknown"]) // nullprintln(scores.getOrDefault("Unknown", 0)) // 0println(scores.getOrElse("Unknown") { -1 }) // -1
// Keys & Valuesprintln(scores.keys) // [Alice, Bob, Charlie]println(scores.values) // [95, 87, 92]
// Entriesfor ((name, score) in scores) { println("$name: $score")}🔄 Mutable Operations
Phần tiêu đề “🔄 Mutable Operations”val map = mutableMapOf("a" to 1)
// Add/Updatemap["b"] = 2map.put("c", 3)map += "d" to 4map.putAll(mapOf("e" to 5, "f" to 6))
// Removemap.remove("a")map -= "b"
// Computemap.compute("c") { _, v -> (v ?: 0) + 10 }map.getOrPut("g") { 7 } // Add if not exists🔗 Transform
Phần tiêu đề “🔗 Transform”val scores = mapOf("Alice" to 95, "Bob" to 87)
// Map valuesval doubled = scores.mapValues { (_, v) -> v * 2 }
// Map keysval lowercase = scores.mapKeys { (k, _) -> k.lowercase() }
// Filterval high = scores.filter { (_, v) -> v >= 90 }
// To list of pairsval pairs = scores.toList() // [(Alice, 95), (Bob, 87)]🛠️ Thực hành
Phần tiêu đề “🛠️ Thực hành”fun main() { val words = "hello world hello kotlin world kotlin kotlin"
// TODO: Đếm tần suất xuất hiện của mỗi từ}Lời giải:
fun main() { val words = "hello world hello kotlin world kotlin kotlin"
val frequency = words.split(" ") .groupingBy { it } .eachCount()
println(frequency) // {hello=2, world=2, kotlin=3}
val mostCommon = frequency.maxByOrNull { it.value } println("Most common: ${mostCommon?.key}") // kotlin}✅ Checklist
Phần tiêu đề “✅ Checklist”- Tạo Map với
toinfix:mapOf("a" to 1) - Truy cập an toàn với
getOrDefault,getOrElse - Duyệt với destructuring:
for ((k, v) in map) - Sử dụng
mapKeys,mapValues,filter
Tiếp theo: Array