Kotlin Map:mapOf()用法及代码示例

56 阅读4分钟

本文方法及代码示例基于 Kotlin 2.1.20 Released

Kotlin映射是包含对象对的集合。 Map 以成对的形式保存数据,由键和值组成。映射键是唯一的,并且映射只为每个键保存一个值。

Kotlin 区分不可变的和可变的Map。使用以下命令创建的不可变MapmapOf() 意味着这些是用以下命令创建的只读且可变的映射mutableMapOf() 意味着我们可以执行读取和写入操作。

一、用法

fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> 
  • 该对的第一个值是钥匙第二个是对应的键。
  • 如果多个对具有相同的键,则映射将返回最后一个对的值。
  • 映射条目按指定的顺序遍历。

示例代码:

fun main(args : Array<String>) {     
    // declaring a map of integer to string     
    val map = mapOf(1 to "Geeks", 2 to "for", 3 to "Geeks")         
    // printing the map         
    println(map) 
}

// 结果:{1=Geeks, 2=for, 3=Geeks}

二、键、值和条目的映射

fun main(args: Array<String>) {     
    //declaring a map of integer to string     
    val map = mapOf(1 to "One", 2 to "Two" , 3 to "Three", 4 to "Four")     println("Map Entries : "+map)     
    println("Map Keys: "+map.keys )     
    println("Map Values: "+map.values ) 
}

// 输出:
Map Entries : {1=One, 2=Two, 3=Three, 4=Four}
Map Keys: [1, 2, 3, 4]
Map Values: [One, Two, Three, Four]

三、Map大小

可以使用两种方法来确定Map的大小。通过使用Map的大小属性并使用count()方法。

fun main() {     
    val ranks = mapOf(1 to "India",2 to "Australia",3 to "England",4 to "Africa")     //method 1     
    println("The size of the map is: "+ranks.size)     
    //method 2     
    println("The size of the map is: "+ranks.count()) 
}

// 输出:
The size of the map is: 4
The size of the map is: 4 

四、空Map

可以使用以下命令创建一个空的serialize-ableMapmapOf()

fun main(args: Array<String>) {     
    //here we have created an empty map using mapOf()     
    val map1 = mapOf<String , Int>()            
    println("Entries: " + map1.entries)  //entries of map        
    println("Keys:" + map1.keys)  //keys of map        
    println("Values:" + map1.values)  //values of map    
}

// 输出:
Entries: []
Keys:[]
Values:[]

五、获取Map的值

可以使用下面示例代码中的不同方法从Map中检索值。

fun main() {     
    val ranks = mapOf(1 to "India",2 to "Australia",3 to "England",4 to "Africa")     //method 1     
    println("Team having rank #1 is: "+ranks[1])     
    //method 2     
    println("Team having rank #3 is: "+ranks.getValue(3))     
    //method 3     
    println("Team having rank #4 is: "+ranks.getOrDefault(4, 0))     
    // method  4     
    val team = ranks.getOrElse(2 ,{ 0 })     
    println(team) 
}

// 输出:
Team having rank #1 is: India
Team having rank #3 is: England
Team having rank #4 is: Africa
Australia

六、映射包含键或值

可以分别使用containsKey()和containsValue()方法来确定映射包含键或值。

fun main() {     
    val colorsTopToBottom = mapOf("red" to 1, "orange" to 2, "yellow" to 3,         "green" to 4 , "blue" to 5, "indigo" to 6, "violet" to 7)     
    var color = "yellow"     
    if (colorsTopToBottom.containsKey(color)) {         
        println("Yes, it contains color $color")     
    } else {         
        println("No, it does not contain color $color")     
    }     
    val value = 8     
    if (colorsTopToBottom.containsValue(value)) {
        println("Yes, it contains value $value")     
    } else {         
        println("No, it does not contain value $value")     
    } 
}

// 输出:
Yes, it contains color yellow
No, it does not contain value 8 

七、两个值和相同的键

如果两个值具有相同的键值,则映射将包含这些数字的最后一个值。

fun main(args: Array<String>) {     
    //lets make two values with same key     
    val map = mapOf(1 to "geeks1",2 to "for" , 1 to "geeks2") // return the map entries     
    println("Entries of map : " + map.entries) 
}

// 输出
Entries of map : [1=geeks2, 2=for]

这里键值1已用两个值初始化:geeks1和geeks2,但据我们所知mapOf()一个关键项只能有一个值,因此最后一个值仅由映射存储,并且geeks1被淘汰。

mapOf() 是 Kotlin 中的一个函数,用于创建新的只读映射。映射是键值对的集合,其中每个键都是唯一的。

八、使用 mapOf() 创建字符串映射的示例:

fun main() {     
    // create a new map     
    val names = mapOf("John" to 25, "Mary" to 30, "Bob" to 20)     
    // get the value associated with a key     
    val johnAge = names["John"]     
    // check if a key is present in the map     
    val containsMary = names.containsKey("Mary")     
    // print the map and the result of the contains check     
    println("Names: $names")     
    println("Contains Mary: $containsMary") 
}

// 输出
Names:{Johm=25,Mary=30,Bob=20}  
Contains Mary:true

九、总结

1、mapOf()的优点:
  1. 映射数据结构提供了一种将键与值关联的方法,这对于组织和检索数据非常有用。
  2. mapOf() 函数易于使用,并提供了一种简单的方法来创建具有初始键值对的新只读映射。
  3. 映射的只读特性使其可以安全地在函数和线程之间传递,而无需担心并发修改。
2、mapOf()的缺点:
  1. Map的只读性质意味着一旦创建就无法修改。要添加或删除元素,您必须创建新映射或使用可变映射。
  2. 如果键值对的数量非常大,则映射数据结构可能会变得低效,因为在最坏的情况下需要 O(n) 时间来搜索键。如果需要执行频繁的查找或修改,则不同的数据结构(例如哈希表或二叉树)可能更合适。

相关用法