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()的優點:
- 映射數據結構提供了一種將鍵與值關聯的方法,這對於組織和檢索數據非常有用。
- mapOf() 函數易於使用,並提供了一種簡單的方法來創建具有初始鍵值對的新隻讀映射。
- 映射的隻讀特性使其可以安全地在函數和線程之間傳遞,而無需擔心並發修改。
mapOf()的缺點:
- Map的隻讀性質意味著一旦創建就無法修改。要添加或刪除元素,您必須創建新映射或使用可變映射。
- 如果鍵值對的數量非常大,則映射數據結構可能會變得低效,因為在最壞的情況下需要 O(n) 時間來搜索鍵。如果需要執行頻繁的查找或修改,則不同的數據結構(例如哈希表或二叉樹)可能更合適。
相關用法
- Kotlin MatchResult.destructured用法及代碼示例
- Kotlin MatchResult.groupValues用法及代碼示例
- Kotlin MatchResult.Destructured用法及代碼示例
- Kotlin maxByOrNull用法及代碼示例
- Kotlin groupByTo用法及代碼示例
- Kotlin OverloadResolutionByLambdaReturnType.<init>用法及代碼示例
- Kotlin reduceRightIndexedOrNull用法及代碼示例
- Kotlin dropWhile用法及代碼示例
- Kotlin takeWhile用法及代碼示例
- Kotlin elementAt用法及代碼示例
- Kotlin chunked用法及代碼示例
- Kotlin filterNot用法及代碼示例
- Kotlin firstNotNullOf用法及代碼示例
- Kotlin BuilderInference用法及代碼示例
- Kotlin minByOrNull用法及代碼示例
- Kotlin titlecase用法及代碼示例
- Kotlin all用法及代碼示例
- Kotlin drop用法及代碼示例
- Kotlin toTypedArray用法及代碼示例
- Kotlin reduceIndexed用法及代碼示例
- Kotlin elementAtOrNull用法及代碼示例
- Kotlin flatten用法及代碼示例
- Kotlin sort用法及代碼示例
- Kotlin Random.<init>用法及代碼示例
- Kotlin filterIsInstanceTo用法及代碼示例
注:本文由純淨天空篩選整理自ManishKhetan大神的英文原創作品 Kotlin Map : mapOf()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。