当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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

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

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

用法:

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

mapOf()的Kotlin程序

科特林


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()

示例2:mapOf()

科特林


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 

两个值和相同的键:

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

示例3:mapOf()

科特林


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已用两个值初始化:极客1和极客2,但据我们所知mapOf() 一个关键项只能有一个值,因此最后一个值仅由映射存储,并且极客1被淘汰。

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")
}

输出

姓名:{约翰=25,玛丽=30,鲍勃=20}
包含玛丽:真实

在此示例中,我们使用 mapOf() 函数创建一个新的只读字符串映射,其中键值对为 “John” 为 25、“Mary” 为 30、“Bob” 为 20。然后,我们检索该值使用方括号表示法与键 “John” 关联并将其存储在变量 johnAge 中。最后,我们使用containsKey()函数检查映射是否包含键“Mary”并将结果打印到控制台。

mapOf()的优点:

  1. 映射数据结构提供了一种将键与值关联的方法,这对于组织和检索数据非常有用。
  2. mapOf() 函数易于使用,并提供了一种简单的方法来创建具有初始键值对的新只读映射。
  3. 映射的只读特性使其可以安全地在函数和线程之间传递,而无需担心并发修改。

mapOf()的缺点:

  1. Map的只读性质意味着一旦创建就无法修改。要添加或删除元素,您必须创建新映射或使用可变映射。
  2. 如果键值对的数量非常大,则映射数据结构可能会变得低效,因为在最坏的情况下需要 O(n) 时间来搜索键。如果需要执行频繁的查找或修改,则不同的数据结构(例如哈希表或二叉树)可能更合适。


相关用法


注:本文由纯净天空筛选整理自ManishKhetan大神的英文原创作品 Kotlin Map : mapOf()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。