Combine collections
Kotlin provides operators and functions for adding and removing collection elements and combining collections. These operations return a new read-only collection, leaving the original collections unchanged.
You can also modify mutable collections by adding or removing elements. For more information, see Change collections.
Add and remove elements
In Kotlin, you can use plus (+) and minus (-) operators to add or remove collection elements. The first operand is a collection, and the second is either an element or another collection. Each operator returns a new read-only collection:
plusreturns a collection containing the original elements and the element or elements from the second operand.minusreturns a collection without the elements specified in the second operand. If that operand is an element,minusremoves its first occurrence. If the second operand is a collection,minusremoves all occurrences of its elements.
You can also use the augmented assignment operators plusAssign (+=) and minusAssign (-=) with collections:
For a read-only collection stored in a variable declared with
var, these operators useplusorminusand assign the resulting collection back to the variable.For a mutable collection stored in a variable declared with
val, these operators useplusAssignorminusAssignto modify the collection in place.
For details on the plus and minus operators for maps, see Map-specific operations.
Merge two collections
To merge two collections, use the union() function. It returns a Set containing distinct elements from both collections. You can also call it in infix form: a union b.
The result preserves the iteration order of the first collection, followed by elements from the second collection that aren't already present, in their iteration order:
Find the intersection of two collections
To find elements present in both collections (their intersection), use intersect(). To find elements present in the first collection but absent from the second, use subtract().
Both functions return a Set and support infix notation (a intersect b and a subtract b):
Find elements present in only one collection
To find elements present only in one of two collections, subtract the collections from each other and combine the results with union(). This operation is called the symmetric difference and returns a Set: