跳转至

Kotlin 映射

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

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

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

Kotlin 映射

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

Kotlin mapOf()

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

KotlinMapOf.kt

package com.zetcode

fun main() {

    val chars = mapOf(97 to "a", 98 to "b", 120 to "x")
    println(chars)

    val user = mapOf("name" to "Luke", "age" to "23")
    println(user)
}

该示例创建了两个映射。

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

这是输出。

Kotlin 哈希映射

可以从 Java 的HashMap创建映射。

KotlinHashMap.kt

package com.zetcode

fun main() {

    val items = HashMap<String, Int>()

    items["A"] = 90
    items["B"] = 80
    items["C"] = 70

    for ((k, v) in items) {
        println("$k = $v")
    }
}

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

Kotlin 映射大小

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

KotlinMapSize.kt

package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

    println("Map has ${items.size} items")
    println("Map has ${items.count()} items")

    val n = items.count { it.value > 10 }
    println("# of values greater that 10: $n")
}

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

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

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

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

这是输出。

Kotlin 条目,键,值

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

KotlinEntriesKeysValues.kt

package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33)

    println("Entries: " + items.entries)
    println("Keys:" + items.keys)
    println("Values:" + items.values)
}

该示例使用entrieskeysvalues属性。

Entries: [coins=12, books=45, cups=33]
Keys:[coins, books, cups]
Values:[12, 45, 33]

这是输出。

Kotlin mutableMapOf

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

KotlinMutableMap.kt

package com.zetcode

fun main() {

    val user = mutableMapOf("name" to "John Doe", "occupation" to "programmer")
    println(user)

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

    user.remove("occupation")
    println(user)

    user.clear()
    println(user)

    if (user.isEmpty()) {
        println("empty")
    } else {
        println("not empty")
    }
}

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

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

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

user.remove("occupation")

remove()删除一对。

user.clear()

clear()删除所有对。

if (user.isEmpty()) {
    println("empty")
} else {
    println("not empty")
}

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

{name=John Doe, occupation=programmer}
{name=John Doe, occupation=programmer, location=USA}
{name=John Doe, location=USA}
{}
empty

这是输出。

Kotlin 获取值

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

KotlinMapGet.kt

package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

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

    println(items.getValue("coins"))

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

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

    println(nOfPencils)
}

该示例从映射获取值。

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

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

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

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

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

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

Kotlin 包含键/值

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

KotlinMapContains.kt

package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

    if (items.containsKey("cups")) {

        println("contains cups")
    } else {

        println("does not contain cups")
    }

    val value = 25

    if (items.containsValue(value)) {

        println("contains value $value")
    } else {

        println("does not contain value $value")
    }
}

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

Kotlin 映射遍历

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

KotlinMapForEach.kt

package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

    items.forEach { (k, v) -> println("There are $v $k") }
}

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

There are 12 coins
There are 45 books
There are 33 cups
There are 2 pens

这是输出。

Kotlin 映射过滤器

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

KotlinMapFilter.kt

package com.zetcode

fun main() {

    val items = mapOf("A" to 90, "B" to 80, "C" to 70, "D" to 60, "E" to 50)

    val filtered = items.filterKeys { it == "A" || it == "C" }
    println(filtered)

    val filtered2 = items.filterValues { it >= 70 }
    println(filtered2)

    val filtered3 = items.filter { it.key == "A" || it.value == 50 }
    println(filtered3)
}

该示例过滤映射。

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

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

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

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

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

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

{A=90, C=70}
{A=90, B=80, C=70}
{A=90, E=50}

这是输出。

Kotlin 有序映射

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

KotlinSortedMap.kt

package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
    println(items)

    val sortedItems = sortedMapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
    println(sortedItems)
}

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

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

这些对按键排序。

Kotlin 映射any()

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

KotlinMapAny.kt

package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

    val value = 12

    val hasValue = items.any { it.value == value }

    if (hasValue) {
        println("The map has value $value")
    } else {
        println("The map does not have value $value")
    }

    val isEven: (Int) -> Boolean = { it % 2 == 0 }

    val hasEvenValue = items.any { isEven(it.value) }

    if (hasEvenValue) {
        println("The map has even value(s)")
    } else {
        println("The map does not have even value(s)")
    }
}

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

The map has value 12
The map has even value(s)

这是输出。

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


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组