Clear a List in Kotlin
This article explores different ways to clear a mutable list in Kotlin.
1. Using clear() function
The standard operation to empty a list is using the clear() function, which efficiently removes all elements from it. This is the best approach in terms of performance. Note that this doesn’t work on unmodifiable lists.
|
1 2 3 4 5 6 |
fun main() { val input = (1..5).toMutableList() input.clear() println(input) // [] } |
2. Using removeAll() function
We can also use the removeAll() function to remove all elements from a mutable list, that matches with any of the elements in the specified input. A typical invocation for this method would look like below to clear a list:
|
1 2 3 4 5 6 |
fun main() { val input = (1..5).toMutableList() input.removeAll(input) println(input) // [] } |
3. Using remove() function
The idea is to get a copy of elements in the list and call the remove() function for each element. The copy of the list is used to avoid ConcurrentModificationException, since concurrent modification of the list is not allowed while iterating over it.
|
1 2 3 4 5 6 |
fun main() { val input = (1..5).toMutableList() input.toList().forEach { input.remove(it) } println(input) // [] } |
4. Using Iterator.remove() function
The iterator’s remove() function doesn’t throw ConcurrentModificationException when some thread modifies the collection while another thread is iterating over it. It can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val input = (1..5).toMutableList() val it = input.listIterator() while (it.hasNext()) { it.next() it.remove() } println(input) // [] } |
That’s all about clearing a mutable 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 :)