Skip to Content
Kotlin📘 Ngôn ngữ Kotlin🗺️ Map (Dictionary)

Map (Dictionary) trong Kotlin

🎯 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

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

// Immutable val map = mapOf("a" to 1, "b" to 2) val empty = emptyMap<String, Int>() // Mutable val 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

val scores = mapOf("Alice" to 95, "Bob" to 87, "Charlie" to 92) // Get println(scores["Alice"]) // 95 println(scores["Unknown"]) // null println(scores.getOrDefault("Unknown", 0)) // 0 println(scores.getOrElse("Unknown") { -1 }) // -1 // Keys & Values println(scores.keys) // [Alice, Bob, Charlie] println(scores.values) // [95, 87, 92] // Entries for ((name, score) in scores) { println("$name: $score") }

🔄 Mutable Operations

val map = mutableMapOf("a" to 1) // Add/Update map["b"] = 2 map.put("c", 3) map += "d" to 4 map.putAll(mapOf("e" to 5, "f" to 6)) // Remove map.remove("a") map -= "b" // Compute map.compute("c") { _, v -> (v ?: 0) + 10 } map.getOrPut("g") { 7 } // Add if not exists

🔗 Transform

val scores = mapOf("Alice" to 95, "Bob" to 87) // Map values val doubled = scores.mapValues { (_, v) -> v * 2 } // Map keys val lowercase = scores.mapKeys { (k, _) -> k.lowercase() } // Filter val high = scores.filter { (_, v) -> v >= 90 } // To list of pairs val pairs = scores.toList() // [(Alice, 95), (Bob, 87)]

🛠️ 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

  • Tạo Map với to infix: 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

Last updated on