Kotlin 映射(Map)
外观
Kotlin 映射(Map)[编辑 | 编辑源代码]
简介[编辑 | 编辑源代码]
映射(Map)是 Kotlin 中一种常用的数据结构,用于存储键值对(Key-Value Pair)。它类似于字典或哈希表,允许通过键(Key)快速查找对应的值(Value)。Kotlin 中的映射分为两种:
- 不可变映射(使用 `mapOf` 创建)
- 可变映射(使用 `mutableMapOf` 创建)
映射的主要特点包括:
- 键必须是唯一的,但值可以重复。
- 键和值可以是任意类型(如 `String`、`Int`、自定义类等)。
- 提供高效的查找、插入和删除操作(平均时间复杂度为 O(1))。
创建映射[编辑 | 编辑源代码]
不可变映射[编辑 | 编辑源代码]
使用 `mapOf` 创建一个不可变的映射(初始化后不能修改):
val immutableMap = mapOf(
"Alice" to 25,
"Bob" to 30,
"Charlie" to 28
)
println(immutableMap) // 输出:{Alice=25, Bob=30, Charlie=28}
可变映射[编辑 | 编辑源代码]
使用 `mutableMapOf` 创建一个可变的映射(可以动态添加或删除键值对):
val mutableMap = mutableMapOf(
"Apple" to 1.99,
"Banana" to 0.99,
"Orange" to 1.49
)
mutableMap["Grapes"] = 2.49 // 添加新键值对
println(mutableMap) // 输出:{Apple=1.99, Banana=0.99, Orange=1.49, Grapes=2.49}
访问映射元素[编辑 | 编辑源代码]
可以通过键来访问映射中的值:
val ageMap = mapOf("Alice" to 25, "Bob" to 30)
println(ageMap["Alice"]) // 输出:25
println(ageMap.get("Bob")) // 输出:30
println(ageMap["Charlie"] ?: "Unknown") // 输出:Unknown(键不存在时返回 null,使用 Elvis 操作符提供默认值)
常用操作[编辑 | 编辑源代码]
遍历映射[编辑 | 编辑源代码]
可以使用 `for` 循环或 `forEach` 遍历映射:
val fruits = mapOf("Apple" to "Red", "Banana" to "Yellow", "Grapes" to "Purple")
// 方式 1:使用 for 循环
for ((fruit, color) in fruits) {
println("$fruit is $color")
}
// 方式 2:使用 forEach
fruits.forEach { (fruit, color) ->
println("$fruit is $color")
}
输出:
Apple is Red Banana is Yellow Grapes is Purple
检查键或值是否存在[编辑 | 编辑源代码]
val capitals = mapOf("France" to "Paris", "Germany" to "Berlin")
println("France" in capitals) // 输出:true(检查键是否存在)
println("Paris" in capitals.values) // 输出:true(检查值是否存在)
过滤映射[编辑 | 编辑源代码]
使用 `filter` 筛选符合条件的键值对:
val numbers = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
val filtered = numbers.filter { (key, value) -> value % 2 == 0 }
println(filtered) // 输出:{two=2, four=4}
实际应用案例[编辑 | 编辑源代码]
案例 1:单词频率统计[编辑 | 编辑源代码]
统计一段文本中每个单词出现的次数:
fun countWords(text: String): Map<String, Int> {
val wordCount = mutableMapOf<String, Int>()
text.split(" ").forEach { word ->
wordCount[word] = wordCount.getOrDefault(word, 0) + 1
}
return wordCount
}
val text = "hello world hello kotlin world"
println(countWords(text)) // 输出:{hello=2, world=2, kotlin=1}
案例 2:用户缓存系统[编辑 | 编辑源代码]
使用映射实现简单的用户缓存:
class UserCache {
private val cache = mutableMapOf<Int, String>()
fun getUser(id: Int): String? {
return cache[id]
}
fun addUser(id: Int, name: String) {
cache[id] = name
}
}
val userCache = UserCache()
userCache.addUser(1, "Alice")
println(userCache.getUser(1)) // 输出:Alice
性能分析[编辑 | 编辑源代码]
Kotlin 的映射默认基于哈希表实现(`HashMap`),其操作的时间复杂度如下:
- 插入:平均 O(1),最坏 O(n)
- 查找:平均 O(1),最坏 O(n)
- 删除:平均 O(1),最坏 O(n)
进阶主题[编辑 | 编辑源代码]
自定义对象作为键[编辑 | 编辑源代码]
如果自定义类要作为映射的键,必须正确实现 `equals()` 和 `hashCode()`:
data class Person(val name: String, val age: Int)
val personMap = mapOf(
Person("Alice", 25) to "Engineer",
Person("Bob", 30) to "Doctor"
)
println(personMap[Person("Alice", 25)]) // 输出:Engineer
排序映射[编辑 | 编辑源代码]
使用 `TreeMap` 实现按键排序的映射:
import java.util.TreeMap
val sortedMap = TreeMap(mapOf("Orange" to 3, "Apple" to 5, "Banana" to 2))
println(sortedMap) // 输出:{Apple=5, Banana=2, Orange=3}(按键字母顺序排序)
总结[编辑 | 编辑源代码]
- 映射是存储键值对的高效数据结构。
- Kotlin 提供不可变(`mapOf`)和可变(`mutableMapOf`)两种映射。
- 支持多种操作,如遍历、过滤、检查存在性等。
- 适用于缓存、频率统计、配置管理等场景。
页面模块:Message box/ambox.css没有内容。
键必须是唯一的,且自定义对象作为键时需要正确实现 `hashCode()` 和 `equals()`。 |