集合部分元素截取

slice()

根据参数中指定的下表返回集合,参数既可以是range, 也可以是整形的集合

1
2
3
4
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.slice(1..3)) // [two, three, four]
println(numbers.slice(0..4 step 2)) // [one, three, five]
println(numbers.slice(setOf(3, 5, 0)))  // [four, six, one]

take & drop

  • take(n) 返回集合的前n个元素, 如果n大于集合元素个数,则返回整个集合

  • takeLast(n) 返回集合的后n个元素, 如果n大于集合元素个数,则返回整个集合

  • drop(n) 返回集合中除了前n个元素之外的元素, 如果n大于集合元素个数,则返回空集合

  • dropLasst(n) 返回集合中除了后n个元素之外的元素, 如果n大于集合元素个数,则返回整个集合

    1
    2
    3
    4
    5
    
    val numbers = listOf("one", "two", "three", "four", "five", "six")
    println(numbers.take(3)) // [one, two, three]
    println(numbers.takeLast(3)) // [four, five, six]
    println(numbers.drop(1)) // [two, three, four, five, six]
    println(numbers.dropLast(5)) // [one]
    
  • takeWhile(predicate)从集合头部往后,直到遇到第一个不满足predicate的元素就停止,然后返回这个元素之前的所有元素(不包括这个元素),如果所有元素都不满足predicate则返回空集合

  • dropwhile(predicate)takeWhie相反,从集合头部往后,直到遇到第一个满足predicate的元素就停止,然后返回这个元素之后所有的元素(包含该元素本身。)如果所有元素都不满足predicate则返回整个集合

  • takeLastWhile(predicate)从集合尾部往前,直到遇到第一个不满足predicate的元素就停止,然后返回这个元素之后的所有元素(不包括这个元素), 如果所有元素都不满足predicate则返回空集合

  • dropLastWhile(predicate), 与dropLastWhile相反,从集合尾部往前,直到遇到第一个满足predicate的元素就停止,然后返回这个元素之前的所有元素(包括这个元素), 如果所有元素都不满足predicate则返回空集合

    1
    2
    3
    4
    5
    
    val chars = listOf('a', 'b', 'c', 'a', 'b', 'c')
    println(chars.takeWhile { it < 'c' })  // [a, b]
    println(chars.dropWhile { it < 'c' }) // [c, a, b, c]
    println(chars.takeLastWhile { it > 'b' }) // [c]
    println(chars.dropLastWhile { it > 'b' }) // [a, b, c, a, b]
    

Chunked()

Chunked(n)把一个集合拆分成多个小集合,每个小集合的元素个数为n

1
2
val numbers = (0..13).toList()
println(numbers.chunked(3)) // [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13]]

它也可以接受一个转换参数,用于在每个chunked上执行操作

1
2
3
val numbers = (0..13).toList()
println(numbers.chunked(3) { it.sum() })  // `it` is a chunk of the original collection
// [3, 12, 21, 30, 25]

Windowed()

Chunked()略微不同的是,它是尽可能的返回可能的组合

1
2
3
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.windowed(3))
// [[one, two, three], [two, three, four], [three, four, five]]

它还接收setp参数和partialWindows参数,以及转换参数

  • step指定步长
  • partialWindows当剩下的元素格式不满足一个window时,是否返回
1
2
3
4
5
6
val numbers = (1..10).toList()
println(numbers.windowed(3))  // [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]
println(numbers.windowed(3, step = 2, partialWindows = false)) // [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9]]
// 下面的结果比上面多了[9, 10]
println(numbers.windowed(3, step = 2, partialWindows = true)) // [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]
println(numbers.windowed(3) { it.sum() }) // [6, 9, 12, 15, 18, 21, 24, 27]

另外,还有一个函数zipWithNext(),它类似windowed(2)的效果,不同的是windowed(2)返回的每个windows都是List,而zipWithNext()返回的是Pair对

1
2
3
4
5
6
7
8
val numbers = listOf("one", "two", "three", "four", "five")

//注意打印结果的细微差别,上面是中括号,下面是小括号
println(numbers.windowed(2)) // [[one, two], [two, three], [three, four], [four, five]]
println(numbers.zipWithNext()) // [(one, two), (two, three), (three, four), (four, five)]

// 同样它可以接收转换参数
println(numbers.zipWithNext() { s1, s2 -> s1.length > s2.length}) // [false, false, true, false]

集合中单个元素获取

根据元素位置获取元素

elementAt()

1
2
3
4
5
val numbers = linkedSetOf("one", "two", "three", "four", "five")
println(numbers.elementAt(3))

val numbersSortedSet = sortedSetOf("one", "two", "three", "four")
println(numbersSortedSet.elementAt(0)) // elements are stored in the ascending order

first()last()

1
2
3
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.first())    // one
println(numbers.last())   // five

elemtnAtOrNull()返回指定索引的元素,当索引值超出集合范围时,返回null

elementAtOrElse() 返回指定索引的元素,当索引值超出集合范围时,返回Lambda表达式的值

1
2
3
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.elementAtOrNull(5)) // null
println(numbers.elementAtOrElse(5) { index -> "The value for index $index is undefined"}) //The value for index 5 is undefined

根据条件获取元素

first()last()函数也可以接受一个predicate参数,用于获取第一个或最后一个满足条件的元素

1
2
3
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.first { it.length > 3 }) // three
println(numbers.last { it.startsWith("f") }) // five

上面的方法中,如果没有元素满足predicate,则会抛出异常,更安全的做法是使用firsOrNull()lastOrNull()

1
2
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.firstOrNull { it.length > 6 }) // null

find()findLast()分别就是firsOrNull()lastOrNull()函数的别名

1
2
3
val numbers = listOf(1, 2, 3, 4)
println(numbers.find { it % 2 == 0 }) // 2
println(numbers.findLast { it % 2 == 0 }) //4

通过选择器选择元素

firstNotNullOf()

Returns the first non-null value produced by transform function being applied to elements of this array in iteration order, or throws NoSuchElementException if no non-null value was produced.

没有找到符合条件的元素时,会抛出NoSuchElementException异常,安全做法是使用firstNotNullOfOrNull(),它在没有找到符合条件的元素时,返回null

1
2
3
4
val list = listOf<Any>(0, "true", false)
// Converts each element to string and returns the first one that has required length
val longEnough = list.firstNotNullOf { item -> item.toString().takeIf { it.length >= 4 } }
println(longEnough) // true

随机获取元素

random()返回一个随机的元素,当集合为空时,会抛出异常,安全的做法是使用randomOrNull()

1
2
val numbers = listOf(1, 2, 3, 4)
println(numbers.random())

检查元素是存在

contains()containsAll()

1
2
3
4
5
6
7
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.contains("four"))
println("zero" in numbers)

//检查是否包含多个元素
println(numbers.containsAll(listOf("four", "two")))
println(numbers.containsAll(listOf("one", "zero")))

isEmpty()isNotEmpty()

1
2
3
4
5
6
7
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.isEmpty()) // false
println(numbers.isNotEmpty()) // true

val empty = emptyList<String>()
println(empty.isEmpty()) // true
println(empty.isNotEmpty())  // false

集合排序

实现可比性

通过实现Comparable接口,可以实现对象直接的大小比较

A - B

  • 返回正数,表示A> B
  • 返回负数, 表示A<B
  • 返回0, 表示两个对象相等
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Version(private val major: Int, private val minor: Int) : Comparable<Version> {
    override fun compareTo(other: Version): Int {
        return when {
            this.major != other.major -> {
                this.major - other.major
            }
            this.minor != other.minor -> {
                this.minor - other.minor
            }
            else -> 0
        }
    }
}

fun main() {
    println(Version(1, 2) > Version(1, 3)) // false
    println(Version(2, 0) > Version(1, 5)) // true
}

通过Comparator定义比较的方式

1
2
val lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))

可以使用compareBy简写

1
println(listOf("aaa", "bb", "c").sortedWith(compareBy { it.length }))

自然排序

sorted()sortedDescending()

1
2
3
4
5
6
val numbers = listOf("one", "two", "three", "four")

println("Sorted ascending: ${numbers.sorted()}")
println("Sorted descending: ${numbers.sortedDescending()}")
// Sorted ascending: [four, one, three, two]
// Sorted descending: [two, three, one, four]

自定义排序方式

sortedBy()sortedByDesending()

1
2
3
4
5
6
7
8
9
val numbers = listOf("one", "two", "three", "four")

val sortedNumbers = numbers.sortedBy { it.length }
println("Sorted by length ascending: $sortedNumbers")
val sortedByLast = numbers.sortedByDescending { it.last() }
println("Sorted by the last letter descending: $sortedByLast")

// Sorted by length ascending: [one, two, four, three]
// Sorted by the last letter descending: [four, two, one, three]

通过sortedWith()compareBy来定义排序

1
2
3
val numbers = listOf("one", "two", "three", "four")
println("Sorted by length ascending: ${numbers.sortedWith(compareBy { it.length })}")
// Sorted by length ascending: [one, two, four, three]

反转排序

reversed(),基于原始集合复制出一个新的集合来排序,排序后的集合和原来的相互独立

1
2
val numbers = listOf("one", "two", "three", "four")
println(numbers.reversed())

asReversed()返回一个会受原始集合影响的集合,

1
2
3
4
5
6
7
    val numbers = mutableListOf("one", "two", "three", "four")
    println(numbers) // [one, two, three, four]
    val reversedNumbers = numbers.asReversed()
    println(numbers) // 反转之后,numbers的本身的顺序不受影响 [one, two, three, four]
    println(reversedNumbers) // [four, three, two, one]
    numbers.add("five")
    println(reversedNumbers) // 原始集合添加了元素, reversedNumbers也添加了元素[five, four, three, two, one]

随机排序

shuffled()函数,将集合的元素随机排序

1
2
val numbers = listOf("one", "two", "three", "four")
println(numbers.shuffled()) // [three, two, four, one]

集合的聚合操作

  • minOrNull() 返回集合中的最小元素,空集合返回null

  • maxOrNull() 返回集合中的最大元素,空集合返回null``

  • average()返回集合的平均数

  • sum()返回集合所有元素的和

  • count() 返回集合元素的个数

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    fun main() {
        val numbers = listOf(6, 42, 10, 4)
    
        println("Count: ${numbers.count()}")
        println("Max: ${numbers.maxOrNull()}")
        println("Min: ${numbers.minOrNull()}")
        println("Average: ${numbers.average()}")
        println("Sum: ${numbers.sum()}")
    }
    // Count: 4
    // Max: 42
    // Min: 4
    // Average: 15.5
    // Sum: 62
    
    • maxByOrNull(),等效于maxOf(),但是当遇到空集合时,后缀会抛出NoSuchElementException
    • minByOrNull(),等效于minOf(), 但是当遇到空集合时,后缀会抛出NoSuchElementException
    • maxWithOrNull()
    • minWithOrNull()
1
2
3
4
5
6
7
val numbers = listOf(5, 42, 10, 4)
val min3Remainder = numbers.minByOrNull { it % 3 }
println(min3Remainder) // 42

val strings = listOf("one", "two", "three", "four")
val longestString = strings.maxWithOrNull(compareBy { it.length })
println(longestString) // three
  • sumOf

    1
    2
    3
    
    val numbers = listOf(5, 42, 10, 4)
    println(numbers.sumOf { it * 2 })
    println(numbers.sumOf { it.toDouble() / 2 })
    

    FoldReduce操作

    fold()reduce依次将元素计算的结果添加应用到下一个元素中,两种的区别是fold接受一个参数作为初始值,而reduce使用集合的第一个元素作为初始值

    1
    2
    3
    4
    5
    6
    
    val numbers = listOf(5, 2, 10, 4)
    
    val sum = numbers.reduce { sum, element -> sum + element }
    println(sum) // 21
    val sumDoubled = numbers.fold(0) { sum, element -> sum + element * 2 }
    println(sumDoubled) // 42
    

    foldRight()reduceRight()的作用一样,只是从集合最后一个元素往前操作

    1
    2
    3
    
    val numbers = listOf(5, 2, 10, 4)
    val sumDoubledRight = numbers.foldRight(0) { element, sum -> sum + element * 2 }
    println(sumDoubledRight) // 42
    

    如果同时要考虑集合的索引,可以使用下面的函数

    • reduceIndexed()

    • foldIndexed()

      1
      2
      3
      4
      5
      6
      
      val numbers = listOf(5, 2, 10, 4)
      val sumEven = numbers.foldIndexed(0) { idx, sum, element -> if (idx % 2 == 0) sum + element else sum }
      println(sumEven) // 15
      
      val sumEvenRight = numbers.foldRightIndexed(0) { idx, element, sum -> if (idx % 2 == 0) sum + element else sum }
      println(sumEvenRight) // 15
      

    上面的操作在集合为空时,都会抛出异常,可以使用下面的安全方法代替

    • reduceOrNull()
    • redceRightOrNull()
    • reduceIndexedOrNull()
    • reduceRightIndexedOrNull()

如果想同时保留操作的中间值,可以使用runningFold()(等效的scan())和runningReduce()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fun main() {
    val numbers = listOf(0, 1, 2, 3, 4, 5)
    val runningReduceSum = numbers.runningReduce { sum, item -> sum + item }
    val runningFoldSum = numbers.runningFold(10) { sum, item -> sum + item }
    println(runningReduceSum) // [0, 1, 3, 6, 10, 15]
    println(runningFoldSum) // [10, 10, 11, 13, 16, 20, 25]
    val transform = { index: Int, element: Int -> "N = ${index + 1}: $element" }
    println(runningReduceSum.mapIndexed(transform).joinToString("\n", "Sum of first N elements with runningReduce:\n"))
    println(runningFoldSum.mapIndexed(transform).joinToString("\n", "Sum of first N elements with runningFold:\n"))
}
//    Sum of first N elements with runningReduce:
//    N = 1: 0
//    N = 2: 1
//    N = 3: 3
//    N = 4: 6
//    N = 5: 10
//    N = 6: 15
//    Sum of first N elements with runningFold:
//    N = 1: 10
//    N = 2: 10
//    N = 3: 11
//    N = 4: 13
//    N = 5: 16
//    N = 6: 20
//    N = 7: 25

集合的写操作

添加元素add()

1
2
3
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
println(numbers)

添加集合addAll()

1
2
3
4
5
6
7
val numbers = mutableListOf(1, 2, 5, 6)
numbers.addAll(arrayOf(7, 8))
println(numbers) // [1, 2, 5, 6, 7, 8]

// 第一个元素指定插入的位置
numbers.addAll(2, setOf(3, 4))
println(numbers) // [1, 2, 3, 4, 5, 6, 7, 8]

也可以直接使用++=运算符

1
2
3
4
5
val numbers = mutableListOf("one", "two")
numbers += "three"
println(numbers) // [one, two, three]
numbers += listOf("four", "five")
println(numbers) // [one, two, three, four, five]

删除元素remove()

1
2
3
4
5
val numbers = mutableListOf(1, 2, 3, 4, 3)
numbers.remove(3)                    // removes the first `3`
println(numbers) // [1, 2, 4, 3]
numbers.remove(5)                    // removes nothing
println(numbers) //[1, 2, 4, 3]
  • removeAll()一次删除多个元素

  • retainAll()removeAll()操作相反,移除所有需要保留的元素

  • clear()清除所有的元素

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
val numbers = mutableListOf(1, 2, 3, 4)
println(numbers) // [1, 2, 3, 4]
numbers.retainAll { it >= 3 }
println(numbers)  // [3, 4]
numbers.clear() // []
println(numbers)

val numbersSet = mutableSetOf("one", "two", "three", "four")
numbersSet.removeAll(setOf("one", "two"))
println(numbersSet) // [three, four]
  • 使用-或者-=运算符号来删除元素

    -一个元素时,删除集合中出现的第一个这个元素

    -一个集合时,删除原集合种所有出现的元素

    1
    2
    3
    4
    5
    6
    
    `val numbers = mutableListOf("one", "two", "three", "three", "four")
    numbers -= "three"
    println(numbers) //  [one, two, three, four]
    numbers -= listOf("four", "five")
    //numbers -= listOf("four")    // does the same as above
    println(numbers)  // [one, two, three]
    

List独有的操作

通过索引获取元素

get(), getOrElse, getOrNull()

1
2
3
4
5
6
val numbers = listOf(1, 2, 3, 4)
println(numbers.get(0))
println(numbers[0])
//numbers.get(5)                         // exception!
println(numbers.getOrNull(5))             // null
println(numbers.getOrElse(5, {it}))        // 5

获取部分元素

1
2
val numbers = (0..13).toList()
println(numbers.subList(3, 6))

获取元素索引

线性搜索

  • indexOf
  • lastIndexOf
  • indexOfFirst
  • indexOfLast
1
2
3
4
5
6
7
val numbers = listOf(1, 2, 3, 4, 2, 5)
println(numbers.indexOf(2)) // 1
println(numbers.lastIndexOf(2)) // 4

val numbers = mutableListOf(1, 2, 3, 4)
println(numbers.indexOfFirst { it > 2})
println(numbers.indexOfLast { it % 2 == 1})

二进制搜索

使用二进制搜索前,必须对List中的元素做排序操作

1
2
3
4
5
6
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println(numbers)
println(numbers.binarySearch("two"))  // 3
println(numbers.binarySearch("z")) // -5
println(numbers.binarySearch("two", 0, 2))  // -3

当元素不可比较时,搜索的时候需要提供一个Comparator

1
2
3
4
5
6
val productList = listOf(
    Product("WebStorm", 49.0),
    Product("AppCode", 99.0),
    Product("DotTrace", 129.0),
    Product("ReSharper", 149.0))
println(productList.binarySearch(Product("AppCode", 99.0), compareBy<Product> { it.price }.thenBy { it.name }))

还可以直接使用标准库中提供的Comparator,如String.CASE_INSENSITIVE_ORDER

1
2
val colors = listOf("Blue", "green", "ORANGE", "Red", "yellow")
println(colors.binarySearch("RED", String.CASE_INSENSITIVE_ORDER)) // 3

List写操作

所有操作直接修改原始List,而不是返回新的List

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 添加元素add, addAll()
val numbers = mutableListOf("one", "five", "six")
numbers.add(1, "two")
numbers.addAll(2, listOf("three", "four"))
println(numbers)

//更新元素
val numbers = mutableListOf("one", "five", "three")
numbers[1] =  "two"
println(numbers)

// 使用fill替换所有元素
val numbers = mutableListOf(1, 2, 3, 4)
numbers.fill(3)
println(numbers) // [3, 3, 3, 3]

// 删除元素
val numbers = mutableListOf(1, 2, 3, 4, 3)
numbers.removeAt(1)
println(numbers)

// 排序
val numbers = mutableListOf("one", "two", "three", "four")

numbers.sort()
println("Sort into ascending: $numbers") // Sort into ascending: [four, one, three, two]
numbers.sortDescending()
println("Sort into descending: $numbers")  // Sort into descending: [two, three, one, four]

numbers.sortBy { it.length }
println("Sort into ascending by length: $numbers") // Sort into ascending by length: [two, one, four, three]
numbers.sortByDescending { it.last() }
println("Sort into descending by the last letter: $numbers") // Sort into descending by the last letter: [four, two, one, three]

numbers.sortWith(compareBy<String> { it.length }.thenBy { it })
println("Sort by Comparator: $numbers") // Sort by Comparator: [one, two, four, three]

numbers.shuffle()
println("Shuffle: $numbers") // Shuffle: [one, three, four, two]

numbers.reverse()
println("Reverse: $numbers") // Reverse: [two, four, three, one]

Set特有的操作

集合操作

  • 合集union

  • 交集intersect

  • 差集subtract

1
2
3
4
5
6
7
8
9
val numbers = setOf("one", "two", "three")

// 可以使用union的中缀形式,union前的元素在结果中也在前面
println(numbers union setOf("four", "five")) // [one, two, three, four, five]
println(setOf("four", "five") union numbers) // [four, five, one, two, three]

println(numbers intersect setOf("two", "one")) // [one, two]
println(numbers subtract setOf("three", "four")) // [one, two]
println(numbers subtract setOf("four", "three")) // same output [one, two]

PS: 集合运算同样可以用在List上,不过返回的值仍然是Set

Map特有的操作

根据key获取value

1
2
3
4
5
6
7
8
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap.get("one"))
println(numbersMap["five"])  //使用索引方式和get(),当key不存在时,返回null
println(numbersMap["one"])
println(numbersMap.getOrDefault("four", 10)) // 返回默认值10
println(numbersMap.getOrElse("four") { 10 }) // 返回lambda的返回值

//numbersMap.getValue("six")      // 使用getValue()函数时,当key不存在时!

获取所有的key和value

1
2
3
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap.keys) // [one, two, three]
println(numbersMap.values) // [1, 2, 3]

过滤元素

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
// 根据key和value过滤
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
println(filteredMap) // {key11=11}

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
//只根据key过滤
val filteredKeysMap = numbersMap.filterKeys { it.endsWith("1") }
//只根据value过滤
val filteredValuesMap = numbersMap.filterValues { it < 10 }

println(filteredKeysMap) // {key1=1, key11=11}
println(filteredValuesMap) // {key1=1, key2=2, key3=3}

加减运算

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// + 操作符号右边同key的值会覆盖操作符左边的值
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap + Pair("four", 4)) // {one=1, two=2, three=3, four=4}
println(numbersMap + Pair("one", 10)) // {one=10, two=2, three=3}
println(numbersMap + mapOf("five" to 5, "one" to 11)) // {one=11, two=2, three=3, five=5}

// - 操作符号是减去单个key或者一个列表
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap - "one") // {two=2, three=3}
println(numbersMap - listOf("two", "four")) // {one=1, three=3}

添加元素

使用put()或者putAll()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// put()添加单个元素
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap.put("three", 3)
println(numbersMap) // {one=1, two=2, three=3}

// 使用putAll()添加多个元素
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap.putAll(setOf("four" to 4, "five" to 5))
println(numbersMap)  // {one=1, two=2, three=3, four=4, five=5}

// 如果key已经存在,会覆盖同名的key
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
val previousValue = numbersMap.put("one", 11)
println("value associated with 'one', before: $previousValue, after: ${numbersMap["one"]}") // value associated with 'one', before: 1, after: 11
println(numbersMap) // {one=11, two=2}

// 使用[]来访问元素
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap["three"] = 3     // calls numbersMap.put("three", 3)
numbersMap += mapOf("four" to 4, "five" to 5)
println(numbersMap)

删除元素

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// remove
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap.remove("one")
println(numbersMap) // {two=2, three=3}
numbersMap.remove("three", 4)            //doesn't remove anything
println(numbersMap) // {two=2, three=3}

// 还可以根据key或者value来删除元素
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "threeAgain" to 3)
numbersMap.keys.remove("one")
println(numbersMap) // {two=2, three=3, threeAgain=3}
numbersMap.values.remove(3) // 只会删除第一个出现的
println(numbersMap) // {two=2, threeAgain=3}

// 同样可以使用 -= 符号
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap -= "two" // {one=1, three=3}
println(numbersMap)
numbersMap -= "five"             //doesn't remove anything
println(numbersMap) // {one=1, three=3}