Collection write support operations for changing the collection contents, for example, adding or removing elements. Adding elements To add a single element to a collection, use the add() function.
fun main()
{
val c1 = mutableListOf(5,6,7,8)
c1.add(5)
println(c1)
}
output [5, 6, 7, 8, 5]
addAll() adds every element of the argument object to a collection. The argument can be an Iterable, a Sequence, or an Array. addAll() adds new elements in the same order as they go in the argument.
val c1 = mutableListOf(8,9,10,11)
c1.addAll(arrayOf(77, 88))
println(c1)
c1.addAll(2, setOf(33, 44))
println(c1)
output
[8, 9, 10, 11, 77, 88]
[8, 9, 33, 44, 10, 11, 77, 88]
in-place version of the plus operator - plusAssign (+=) When applied to a mutable collection, += appends the second operand (an element or another collection) to the end of the collection.
val c1 = mutableListOf("four", "five")
c1 += "six" println(c1)
output
[four, five, six]
Removing elements
remove() accepts the element value and removes one occurrence of this value.
val c1 = mutableListOf(11,12,13,14,15)
c1.remove(13) // removes the first `3`
println(c1)
c1.remove(55) // removes nothing
println(c1)
`
output
[11, 12, 14, 15]
[11, 12, 14, 15]
some more functions for removing multiple elements at once.
removeAll() removes all elements that are present in the argument collection.
val c1 = mutableSetOf("ten", "twenty", "thirty", "fourty")
c1.removeAll(setOf("ten", "twenty"))
println(c1)
output
[thirty, fourty]
retainAll() is the opposite of removeAll(): it removes all elements except the ones from the argument collection.
val c1 = mutableSetOf("ten", "twenty", "thirty", "fourty")
c1.retainAll { it == "thirty" }
println(c1)
output
[thirty]
clear() removes all elements from a list and leaves it empty.
val c1 = mutableSetOf("ten", "twenty", "thirty", "fourty")
c1.clear()
println(c1)
output
[]