Delete an element from a List in Kotlin
This article explores different ways to delete an element from a List in Kotlin.
1. Using removeAll() function
The removeAll() function removes all elements from the list that are present in the specified collection. The idea is to pass a singleton set containing the specified element to remove it from the list, as shown below:
|
1 2 3 4 5 6 7 8 |
fun main() { val values = mutableListOf(1, 7, 4, 9, 6, 8, 9, 2) val target = 6 values.removeAll(setOf(target)) println(values) // [5, 3, 4, 7, 2, 9] } |
2. Using removeIf() function
Alternatively, you can use the removeIf() function to remove all elements from the list satisfying the provided predicate.
|
1 2 3 4 5 6 7 8 |
fun main() { val values = mutableListOf(1, 7, 4, 9, 6, 8, 9, 2) val target = 6 values.removeIf { it == target } println(values) // [5, 3, 4, 7, 2, 9] } |
3. Using remove() function
The remove() function removes the first occurrence of an element from the list. To remove all occurrences, repeatedly call the remove() function until it returns false. This approach works but is highly inefficient.
|
1 2 3 4 5 6 7 |
fun main() { val values = mutableListOf(1, 7, 4, 9, 6, 8, 9, 2) val target = 6 while (values.remove(target)) println(values) // [5, 3, 4, 7, 2, 9] } |
That’s all about deleting an element from a List in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)