Collection Write Operations | Kotlin

Removing elements

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 }

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 true.

  • 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.

fun main() { //sampleStart 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) //sampleEnd }

Another way to remove elements from a collection is with the minusAssign (-=) 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) //sampleEnd }

Tag » Add Element List Kotlin