Collection write operations
Mutable collections support operations for changing the collection contents, for example, adding or removing elements. On this page, we'll describe write operations available for all implementations of
MutableCollection. For more specific operations available for
Map, see List-specific Operations and Map Specific Operations respectively.
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.
addAll() adds every element of the argument object to a list or a set. The argument can be an
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
When called on lists,
addAll() adds new elements in the same order as they go in the argument. You can also call
addAll() specifying an element position as the first argument. The first element of the argument collection will be inserted at this position. Other elements of the argument collection will follow it, shifting the receiver elements to the end.
You can also add elements using the in-place version of the
+=) 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() accepts the element value and removes one occurrence of this value.
For removing multiple elements at once, there are the following functions :
removeAll()removes all elements that are present in the argument collection. Alternatively, you can call it with a predicate as an argument; in this case the function removes all elements for which the predicate yields
retainAll()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.
Lists and maps also provide operations for updating elements. They are described in List-specific Operations and Map Specific Operations. For sets, updating doesn't make sense since it's actually removing an element and adding another one.