Kotlin 简明教程

Kotlin - Maps

Kotlin map 是一个键/值对的集合,其中每个键都是唯一的,并且它只能与一个值关联。但是,相同的值可以与多个键关联。我们可以将键和值声明为任何类型;没有限制。

Kotlin map is a collection of key/value pairs, where each key is unique, and it can only be associated with one value. The same value can be associated with multiple keys though. We can declare the keys and values to be any type; there are no restrictions.

Kotlin map 可以是可变的 ( mutableMapOf ) 或只读的 ( mapOf )。

A Kotlin map can be either mutable (mutableMapOf) or read-only (mapOf).

在其他编程语言中,映射也称为字典或关联数组。

Maps are also known as dictionaries or associative arrays in other programming languages.

Creating Kotlin Maps

对于地图创建,使用标准库函数 mapOf() 适用于只读地图, mutableMapOf() 适用于可变地图。

For map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for mutable maps.

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Creating Map using HashMap

Kotlin map 可以从 Java 的 HashMap 创建。

A Kotlin map can be created from Java’s HashMap.

Example

fun main() {
    val theMap = HashMap<String, Int>()

    theMap["one"] = 1
    theMap["two"] = 2
    theMap["three"] = 3
    theMap["four"] = 4

    println(theMap)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Using Pair while Creating Map

我们可以使用 Pair() 方法创建键/值对:

We can use Pair() method to create key/value pairs:

Example

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

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Kotlin Properties

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

Kotlin map has properties to get all entries, keys, and values of the 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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Loop through Kotlin Maps

遍历 Kotlin Maps 有多种方法。让我们逐个研究它们:

There are various ways to loop through a Kotlin Maps. Lets study them one by one:

Using toString() function

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

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Using Iterator

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Using For Loop

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Using 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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Size of Kotlin Map

我们可以使用 size 属性或 count() 方法来获取映射中的元素总数:

We can use size property or count() method to get the total number of elements in a map:

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Size of the Map 4
Size of the Map 4

The containsKey() & containsValue() Methods

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

The The containsKey() checks if the map contains a key. The containsValue() checks if the map contains a value.

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

true
false

The isEmpty() Method

isEmpty() 方法返回 true(不包含元素)如果集合为空,否则返回 false。

The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise.

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

false

The get() Method

get() 方法可以用来获取对应于给定键的值。简写 [key] 语法也受支持。

The get() method can be used to get the value corresponding to the given key. The shorthand [key] syntax is also supported.

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

The value for key two 2
The value for key two 2

Map Addition

我们可以使用 + 运算符将两个或多个映射添加到一个集合中。这将把第二个映射添加到第一个映射中,丢弃重复的元素。

We can use + operator to add two or more maps into a single set. This will add second map into first map, discarding the duplicate elements.

如果两个映射中有重复的键,则第二个映射的键将覆盖前面的映射键。

If there are duplicate keys in two maps then second map’s key will override the previous map key.

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Map Subtraction

我们可以使用 - 运算符从映射中减去 list 。此操作将从映射中删除列表中所有键并返回结果。

We can use - operator to subtract a list from a map. This operation will remove all the keys of the list from the map and will return the result.

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

{two=2, three=3}

Removing Entries from Map

我们可以使用 remove() 方法从可变映射中删除元素,或者我们可以使用减去分配 (-=) 运算符来执行相同操作

We can use remove() method to remove the element from a mutable map, or we can use minus-assign (-=) operator to perform the same operation

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Sorting Map Elements

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

We can use toSortedMap() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order.

您还可以使用 sortedMapOf() 方法创建一个包含给定键/值的排序映射。只要将此方法用在 mapOf() 的位置即可。

You can also create a sorted map with the given key/values using sortedMapOf() method. Just use this method in place of mapOf().

Example

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

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Filtering Map Elements

我们可以使用 filterKeys()filterValues() 方法来过滤出条目。

We can use either filterKeys() or filterValues() method to filter out the entries.

我们还可以使用 filter() 方法来过滤出与键/值都匹配的元素

We can also use filter() method to filter out the elements matching the both key/value

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Mapping Map Elements

我们可以使用 map() 方法使用提供的函数映射所有元素:

We can use map() method to map all elements using the provided function:.

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

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

Kotlin Mutable Map

我们可以使用 mutableMapOf() 创建可变集合,稍后我们可以使用 put 向同一映射中添加更多元素,并且我们可以使用 remove() 方法从集合中删除元素。

We can create mutable set using mutableMapOf(), later we can use put to add more elements in the same map, and we can use remove() method to remove the elements from the set.

Example

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 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

{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}