Collection Write Operations
To add a single element to a list or a set, use the add()
function. The specified object is appended to the end of the collection.
adds every element of the argument object to a list or a set. The argument can be an Iterable
, a Sequence
, or an Array
. The types of the receiver and the argument may be different, for example, you can add all items from a Set
to a List
.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 5, 6)
numbers.addAll(arrayOf(7, 8))
println(numbers)
numbers.addAll(2, setOf(3, 4))
}
You can also add elements using the in-place version of the plus
operator - (+=
) When applied to a mutable collection, +=
appends the second operand (an element or another collection) to the end of the collection.
To remove an element from a mutable collection, use the remove()
function. remove()
accepts the element value and removes one occurrence of this value.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 3, 4, 3)
numbers.remove(3) // removes the first `3`
println(numbers)
numbers.remove(5) // removes nothing
println(numbers)
//sampleEnd
}
- is the opposite of
removeAll()
: it removes all elements except the ones from the argument collection. When used with a predicate, it leaves only elements that match it. clear()
removes all elements from a list and leaves it empty.
Another way to remove elements from a collection is with the (-=
) operator – the in-place version of minus
. The second argument can be a single instance of the element type or another collection. With a single element on the right-hand side, -=
removes the first occurrence of it. In turn, if it’s a collection, all occurrences of its elements are removed. For example, if a list contains duplicate elements, they are removed at once. The second operand can contain elements that are not present in the collection. Such elements don’t affect the operation execution.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "three", "four")
numbers -= "three"
println(numbers)
numbers -= listOf("four", "five")
//numbers -= listOf("four") // does the same as above
println(numbers)
Lists and maps also provide operations for updating elements. They are described in and Map Specific Operations. For sets, updating doesn’t make sense since it’s actually removing an element and adding another one.