Kotlin List – Remove all Occurrences of an Element

We can modify the contents of a List only if the list is mutable.

To remove the first occurrence of a specific element from a Mutable List in Kotlin, call remove() function on this list object and pass the element as argument.

To remove all the occurrences, repeat the above process until there is no occurrence of this element in this list. We may use while loop for repeating the process.

Examples

In the following program, we will create a mutable list with some elements in it. We shall then remove the element 9 repeatedly until all its occurrences in this list are removed.

Main.kt

fun main(args: Array<String>) {
    val mutableList: MutableList<Int> = mutableListOf(1, 4, 9, 16, 9, 25, 9)
    println("List before removing : " + mutableList)
    val element = 9
    while (mutableList.contains(element)) {
        mutableList.remove(element)
    }
    println("List after  removing : " + mutableList)
}

Output

List before removing : [1, 4, 9, 16, 9, 25, 9]
List after  removing : [1, 4, 16, 25]

All the occurrences of the specified element are removed from the list.

Conclusion

In this Kotlin Tutorial, we learned how to remove all the occurrences of specific element from a mutable list in Kotlin, using remove() function in while loop, with the help of example programs.