Kotlin - 地圖



Kotlin map 是一個鍵值對的集合,其中每個鍵都是唯一的,並且只能與一個值關聯。雖然同一個值可以與多個鍵關聯。我們可以宣告鍵和值為任何型別;沒有限制。

Kotlin map 可以是可變的(mutableMapOf)或只讀的(mapOf)。

在其他程式語言中,地圖也稱為字典或關聯陣列。

建立 Kotlin 地圖

對於地圖建立,請使用標準庫函式 mapOf() 用於只讀地圖,mutableMapOf() 用於可變地圖。

可以透過將其轉換為 Map 來獲得可變地圖的只讀檢視。

示例

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    println(theMap)
    
    val theMutableMap = mutableSetOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    println(theMutableMap)
}

執行上述 Kotlin 程式時,將生成以下輸出

{one=1, two=2, three=3, four=4}
[(one, 1), (two, 2), (three, 3), (four, 4)]

使用 HashMap 建立地圖

可以從 Java 的 HashMap 建立 Kotlin map。

示例

fun main() {
    val theMap = HashMap<String, Int>()
    
    theMap["one"] = 1
    theMap["two"] = 2
    theMap["three"] = 3
    theMap["four"] = 4
    
    println(theMap)
}

執行上述 Kotlin 程式時,將生成以下輸出

{four=4, one=1, two=2, three=3}

建立地圖時使用 Pair

我們可以使用 Pair() 方法建立鍵值對

示例

fun main() {
    val theMap = mapOf(Pair("one", 1), Pair("two", 2), Pair("three", 3))
    println(theMap)
}

執行上述 Kotlin 程式時,將生成以下輸出

{one=1, two=2, three=3}

Kotlin 屬性

Kotlin map 具有獲取地圖的所有條目、鍵和值的屬性。

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
    println("Entries: " + theMap.entries)
    println("Keys:" + theMap.keys)
    println("Values:" + theMap.values)
}

執行上述 Kotlin 程式時,將生成以下輸出

Entries: [one=1, two=2, three=3, four=4]
Keys:[one, two, three, four]
Values:[1, 2, 3, 4]

遍歷 Kotlin 地圖

有多種方法可以遍歷 Kotlin 地圖。讓我們逐一學習它們

使用 toString() 函式

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    println(theMap.toString())
}

執行上述 Kotlin 程式時,將生成以下輸出

{one=1, two=2, three=3, four=4}

使用迭代器

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
    val itr = theMap.keys.iterator()
    while (itr.hasNext()) {
        val key = itr.next()
        val value = theMap[key]
        println("${key}=$value")
    }
}

執行上述 Kotlin 程式時,將生成以下輸出

one=1
two=2
three=3
four=4

使用 For 迴圈

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
   for ((k, v) in theMap) {
      println("$k = $v")
   }
   
}

執行上述 Kotlin 程式時,將生成以下輸出

one = 1
two = 2
three = 3
four = 4

使用 forEach

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
   theMap.forEach { 
      k, v -> println("Key = $k, Value = $v") 
   }
}

執行上述 Kotlin 程式時,將生成以下輸出

Key = one, Value = 1
Key = two, Value = 2
Key = three, Value = 3
Key = four, Value = 4

Kotlin 地圖的大小

我們可以使用 size 屬性或 count() 方法獲取地圖中元素的總數

示例

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
    println("Size of the Map " + theMap.size)
    println("Size of the Map " + theMap.count())
}

執行上述 Kotlin 程式時,將生成以下輸出

Size of the Map 4
Size of the Map 4

containsKey() 和 containsValue() 方法

containsKey() 檢查地圖是否包含鍵。containsValue() 檢查地圖是否包含值。

示例

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)

   if(theMap.containsKey("two")){
      println(true)
   }else{
      println(false)
   }
   
   if(theMap.containsValue("two")){
      println(true)
   }else{
      println(false)
   } 
}

執行上述 Kotlin 程式時,將生成以下輸出

true
false

isEmpty() 方法

如果集合為空(不包含任何元素),則 isEmpty() 方法返回 true,否則返回 false。

示例

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
   if(theMap.isEmpty()){
      println(true)
   }else{
      println(false)
   }
}

執行上述 Kotlin 程式時,將生成以下輸出

false

get() 方法

get() 方法可用於獲取與給定鍵對應的值。還支援簡寫 [key] 語法。

示例

fun main() {
   val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)

   println("The value for key two " + theMap.get("two"))
   println("The value for key two " + theMap["two"])
}

執行上述 Kotlin 程式時,將生成以下輸出

The value for key two 2
The value for key two 2
還有一個函式 getValue(),其行為略有不同:如果地圖中找不到鍵,它會丟擲異常。

地圖新增

我們可以使用 + 運算子將兩個或多個地圖新增到單個集合中。這會將第二個地圖新增到第一個地圖中,丟棄重複的元素。

如果兩個地圖中存在重複的鍵,則第二個地圖的鍵將覆蓋前一個地圖的鍵。

示例

fun main() {
    val firstMap = mapOf("one" to 1, "two" to 2, "three" to 3)
    val secondMap = mapOf("one" to 10, "four" to 4)
    val resultMap = firstMap + secondMap
    
    println(resultMap)
}

執行上述 Kotlin 程式時,將生成以下輸出

{one=10, two=2, three=3, four=4}

地圖減法

我們可以使用 - 運算子從地圖中減去一個 列表。此操作將從地圖中刪除列表的所有鍵,並返回結果。

示例

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3)
    val theKeyList = listOf("one", "four")
    val resultMap = theMap - theKeyList
    
    println(resultMap)
}

執行上述 Kotlin 程式時,將生成以下輸出

{two=2, three=3}

從地圖中刪除條目

我們可以使用 remove() 方法從可變地圖中刪除元素,或者可以使用減號賦值 (-=) 運算子執行相同的操作

示例

fun main() {
    val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    theMap.remove( "two")
    println(theMap)
    
    theMap -= listOf("three")
    println(theMap)
}

執行上述 Kotlin 程式時,將生成以下輸出

{one=1, three=3, four=4}
{one=1, four=4}

排序地圖元素

我們可以使用 toSortedMap() 方法按升序排序元素,或使用 sortedDescending() 方法按降序排序集合元素。

您還可以使用 sortedMapOf() 方法使用給定的鍵值建立排序地圖。只需將此方法替換為 mapOf() 即可。

示例

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    var resultMap = theMap.toSortedMap()
    println(resultMap)
}

執行上述 Kotlin 程式時,將生成以下輸出

{four=4, one=1, three=3, two=2}

過濾地圖元素

我們可以使用 filterKeys()filterValues() 方法過濾掉條目。

我們還可以使用 filter() 方法過濾掉匹配鍵/值的元素

.

示例

fun main() {
    val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    var resultMap = theMap.filterValues{ it > 2}
    println(resultMap)
    
    resultMap = theMap.filterKeys{ it == "two"}
    println(resultMap)
    
    resultMap = theMap.filter{ it.key == "two" || it.value == 4}
    println(resultMap)
    
}

執行上述 Kotlin 程式時,將生成以下輸出

{three=3, four=4}
{two=2}
{two=2, four=4}

對映地圖元素

我們可以使用 map() 方法使用提供的函式對映所有元素:。

示例

fun main() {
     val theMap = mapOf("one" to 1, "two" to 2, "three" to 3)
    val resultMap = theMap.map{ (k, v) -> "Key is $k, Value is $v" }
    
    println(resultMap)
}

執行上述 Kotlin 程式時,將生成以下輸出

[Key is one, Value is 1, Key is two, Value is 2, Key is three, Value is 3]

Kotlin 可變地圖

我們可以使用 mutableMapOf() 建立可變集合,稍後我們可以使用 put 在同一地圖中新增更多元素,並且可以使用 remove() 方法從集合中刪除元素。

示例

fun main() {
     val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
    
    theMap.put("four", 4)
    println(theMap)
    
    theMap["five"] = 5
    println(theMap)
    
    theMap.remove("two")
    println(theMap)
    
}

執行上述 Kotlin 程式時,將生成以下輸出

{one=1, two=2, three=3, four=4}
{one=1, two=2, three=3, four=4, five=5}
{one=1, three=3, four=4, five=5}

測驗時間 (面試和考試準備)

Q 1 - 我們可以將可變的 Kotlin 地圖設為不可變的嗎?

A - 是的

B - 否

答案:A

解釋

是的,我們可以透過將可變集合轉換為 Map 來使其不可變

Q 2 - 我們可以新增兩個或多個地圖並使用 + 運算子建立一個單一集合

A - 正確

B - 錯誤

答案:A

解釋

是的,我們可以新增或減去兩個 Kotlin 地圖並生成第三個集合。加號就像集合的 union()

Q 2 - 哪個方法將返回 Kotlin Map 給定鍵的值?

A - get()

B - elementAt()

C - 使用集合變數的直接索引

D - 以上都不是

答案:A

解釋

get() 方法用於獲取與鍵對應的值。

廣告

© . All rights reserved.