原文: http://zetcode.com/kotlin/maps/

Kotlin 映射教程显示了如何在 Kotlin 中使用映射。 映射是对象对的集合。

Kotlin 区分只读映射和可变映射。 使用mapOf()创建只读映射,并使用mutableMapOf()创建可变映射。

Kotlin 映射

映射是保存成对对象的集合。 每对都包含一个键和一个值。 映射键是唯一的; 该映射的每个键仅包含一个值。

Kotlin mapOf()

mapOf()方法创建具有指定内容的只读映射,并以成对的列表的形式给出,其中第一个值为键,第二个为值。

KotlinMapOf.kt

  1. package com.zetcode
  2. fun main() {
  3. val chars = mapOf(97 to "a", 98 to "b", 120 to "x")
  4. println(chars)
  5. val user = mapOf("name" to "Luke", "age" to "23")
  6. println(user)
  7. }

该示例创建了两个映射。

  1. {97=a, 98=b, 120=x}
  2. {name=Luke, age=23}

这是输出。

Kotlin 哈希映射

可以从 Java 的HashMap创建映射。

KotlinHashMap.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = HashMap<String, Int>()
  4. items["A"] = 90
  5. items["B"] = 80
  6. items["C"] = 70
  7. for ((k, v) in items) {
  8. println("$k = $v")
  9. }
  10. }

该示例使用 Java 的HashMap创建映射,并将值和对打印到控制台。

Kotlin 映射大小

映射的大小(对数)可以使用size属性和count()方法确定。

KotlinMapSize.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
  4. println("Map has ${items.size} items")
  5. println("Map has ${items.count()} items")
  6. val n = items.count { it.value > 10 }
  7. println("# of values greater that 10: $n")
  8. }

该示例计算映射对的数量。

  1. val n = items.count { it.value > 10 }

使用count()方法,我们可以计算出大于十的值。

  1. Map has 4 items
  2. Map has 4 items
  3. # of values greater that 10: 3

这是输出。

Kotlin 条目,键,值

Kotlin 映射具有可获取所有条目,键和值的属性。

KotlinEntriesKeysValues.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = mapOf("coins" to 12, "books" to 45, "cups" to 33)
  4. println("Entries: " + items.entries)
  5. println("Keys:" + items.keys)
  6. println("Values:" + items.values)
  7. }

该示例使用entrieskeysvalues属性。

  1. Entries: [coins=12, books=45, cups=33]
  2. Keys:[coins, books, cups]
  3. Values:[12, 45, 33]

这是输出。

Kotlin mutableMapOf

使用mutableMapOf()创建一个可变映射。

KotlinMutableMap.kt

  1. package com.zetcode
  2. fun main() {
  3. val user = mutableMapOf("name" to "John Doe", "occupation" to "programmer")
  4. println(user)
  5. // user.put("location", "USA")
  6. user["location"] = "USA"
  7. println(user)
  8. user.remove("occupation")
  9. println(user)
  10. user.clear()
  11. println(user)
  12. if (user.isEmpty()) {
  13. println("empty")
  14. } else {
  15. println("not empty")
  16. }
  17. }

该示例创建一个可变映射并介绍其方法。

  1. // user.put("location", "USA")
  2. user["location"] = "USA"
  3. println(user)

新对将添加到映射。 IntelliJ IDEA 建议分配操作。

  1. user.remove("occupation")

remove()删除一对。

  1. user.clear()

clear()删除所有对。

  1. if (user.isEmpty()) {
  2. println("empty")
  3. } else {
  4. println("not empty")
  5. }

isEmpty()方法检查映射是否为空。

  1. {name=John Doe, occupation=programmer}
  2. {name=John Doe, occupation=programmer, location=USA}
  3. {name=John Doe, location=USA}
  4. {}
  5. empty

这是输出。

Kotlin 获取值

有几种方法可以从 Kotlin 映射中检索值。

KotlinMapGet.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
  4. // println(items.get("coins"))
  5. println(items["coins"])
  6. println(items.getValue("coins"))
  7. println(items.getOrDefault("pens", 0))
  8. println(items.getOrDefault("pencils", 0))
  9. val nOfPencils = items.getOrElse("pencils", {
  10. 0
  11. })
  12. println(nOfPencils)
  13. }

该示例从映射获取值。

  1. // println(items.get("coins"))
  2. println(items["coins"])

IntelliJ IDEA 建议使用索引操作代替get()

  1. println(items.getOrDefault("pens", 0))

getOrDefault()返回与键对应的值,或者如果不存在键,则返回指定的默认值。

  1. val nOfPencils = items.getOrElse("pencils", {
  2. 0
  3. })

getOrElse()返回给定键的值,或者如果没有给定键的条目,则返回指定函数的结果。

Kotlin 包含键/值

containsKey()检查映射是否包含键。 containsValue()检查映射是否包含值。

KotlinMapContains.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
  4. if (items.containsKey("cups")) {
  5. println("contains cups")
  6. } else {
  7. println("does not contain cups")
  8. }
  9. val value = 25
  10. if (items.containsValue(value)) {
  11. println("contains value $value")
  12. } else {
  13. println("does not contain value $value")
  14. }
  15. }

该示例检查映射是否包含键"cups"和值 25。

Kotlin 映射遍历

使用forEach(),我们可以遍历映射。

KotlinMapForEach.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
  4. items.forEach { (k, v) -> println("There are $v $k") }
  5. }

该示例使用forEach()遍历映射。

  1. There are 12 coins
  2. There are 45 books
  3. There are 33 cups
  4. There are 2 pens

这是输出。

Kotlin 映射过滤器

我们可以使用filterKeys()filterValues()filter()过滤映射。

KotlinMapFilter.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = mapOf("A" to 90, "B" to 80, "C" to 70, "D" to 60, "E" to 50)
  4. val filtered = items.filterKeys { it == "A" || it == "C" }
  5. println(filtered)
  6. val filtered2 = items.filterValues { it >= 70 }
  7. println(filtered2)
  8. val filtered3 = items.filter { it.key == "A" || it.value == 50 }
  9. println(filtered3)
  10. }

该示例过滤映射。

  1. val filtered = items.filterKeys { it == "A" || it == "C" }

我们过滤出所有与指定键匹配的对。

  1. val filtered2 = items.filterValues { it >= 70 }

我们过滤出所有与指定值匹配的对。

  1. val filtered3 = items.filter { it.key == "A" || it.value == 50 }

在这里,我们过滤出与给定键或值匹配的所有对。

  1. {A=90, C=70}
  2. {A=90, B=80, C=70}
  3. {A=90, E=50}

这是输出。

Kotlin 有序映射

使用sortedMapOf()创建排序的映射。

KotlinSortedMap.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
  4. println(items)
  5. val sortedItems = sortedMapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
  6. println(sortedItems)
  7. }

该示例打印未排序和排序的映射。

  1. {coins=12, books=45, cups=33, pens=2}
  2. {books=45, coins=12, cups=33, pens=2}

这些对按键排序。

Kotlin 映射any()

如果至少一个条目与给定谓词匹配,则any()方法返回true

KotlinMapAny.kt

  1. package com.zetcode
  2. fun main() {
  3. val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
  4. val value = 12
  5. val hasValue = items.any { it.value == value }
  6. if (hasValue) {
  7. println("The map has value $value")
  8. } else {
  9. println("The map does not have value $value")
  10. }
  11. val isEven: (Int) -> Boolean = { it % 2 == 0 }
  12. val hasEvenValue = items.any { isEven(it.value) }
  13. if (hasEvenValue) {
  14. println("The map has even value(s)")
  15. } else {
  16. println("The map does not have even value(s)")
  17. }
  18. }

在该示例中,我们检查映射是否包含至少一个值 12,以及是否存在至少一个偶数值。

  1. The map has value 12
  2. The map has even value(s)

这是输出。

在本教程中,我们介绍了 Kotlin 映射。 您可能也对相关的 Kotlin 教程感兴趣: Kotlin 设置教程Kotlin 数组教程或列出所有 Kotlin 教程