9.1.1.9.3 集合的写操作
原文链接: https://kotlinlang.org/docs/collection-write.html
9.1.1.9.3 集合的写操作
可变集合支持用于修改集合内容的操作,例如添加或移除元素。本页将介绍所有 MutableCollection 实现都可用的写操作。关于 List 和 Map 可用的更具体的操作,请分别参阅 List 特有操作和映射特有操作。
添加元素
要向列表或集添加单个元素,请使用 add() 函数。指定的对象会被追加到集合末尾。
1
2
3
4
5
6
|
fun main() {
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
println(numbers)
}
|
addAll() 会把实参对象的每个元素添加到列表或集中。实参可以是 Iterable、Sequence 或 Array。接收者和实参的类型可以不同,例如你可以把一个 Set 中的所有项添加到 List 中。
在列表上调用时,addAll() 会按照实参中的顺序添加新元素。你也可以把元素位置作为第一个实参传给 addAll()。实参集合的第一个元素会被插入到这个位置,实参集合的其他元素紧随其后,接收者的元素则被向后移动。
1
2
3
4
5
6
7
8
|
fun main() {
val numbers = mutableListOf(1, 2, 5, 6)
numbers.addAll(arrayOf(7, 8))
println(numbers)
numbers.addAll(2, setOf(3, 4))
println(numbers)
}
|
你也可以用 plus 运算符的原地版本——plusAssign(+=)来添加元素。当应用于可变集合时,+= 会把第二个操作数(一个元素或另一个集合)追加到集合末尾。
1
2
3
4
5
6
7
8
|
fun main() {
val numbers = mutableListOf("one", "two")
numbers += "three"
println(numbers)
numbers += listOf("four", "five")
println(numbers)
}
|
移除元素
要从可变集合中移除元素,请使用 remove() 函数。remove() 接收元素值,并移除该值的一次出现。
1
2
3
4
5
6
7
8
|
fun main() {
val numbers = mutableListOf(1, 2, 3, 4, 3)
numbers.remove(3) // 移除第一个 `3`
println(numbers)
numbers.remove(5) // 什么都不移除
println(numbers)
}
|
要一次移除多个元素,可以使用以下函数:
removeAll() 会移除实参集合中存在的所有元素。你也可以传入一个谓词作为实参;此时该函数会移除所有让谓词返回 true 的元素。retainAll() 与 removeAll() 相反:它移除除实参集合中的元素之外的所有元素。与谓词一起使用时,它只保留匹配该谓词的元素。clear() 会移除列表中的所有元素,使其为空。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
fun main() {
val numbers = mutableListOf(1, 2, 3, 4)
println(numbers)
numbers.retainAll { it >= 3 }
println(numbers)
numbers.clear()
println(numbers)
val numbersSet = mutableSetOf("one", "two", "three", "four")
numbersSet.removeAll(setOf("one", "two"))
println(numbersSet)
}
|
从集合中移除元素的另一种方式是使用 minusAssign(-=)运算符——即 minus 的原地版本。第二个实参可以是该元素类型的单个实例,也可以是另一个集合。当右侧是单个元素时,-= 会移除它的第一次出现。反之,如果它是一个集合,则会移除其元素的所有出现。例如,如果列表包含重复元素,它们会被一次性移除。第二个操作数可以包含集合中不存在的元素,这类元素不会影响操作的执行。
1
2
3
4
5
6
7
8
9
|
fun main() {
val numbers = mutableListOf("one", "two", "three", "three", "four")
numbers -= "three"
println(numbers)
numbers -= listOf("four", "five")
// numbers -= listOf("four") // 效果与上面相同
println(numbers)
}
|
更新元素
列表和映射也提供了更新元素的操作。它们在 List 特有操作和映射特有操作中介绍。对于集来说,更新没有意义,因为那实际上就是移除一个元素并添加另一个元素。