Conditionally remove elements from a list in Kotlin
This article explores different ways to conditionally remove elements from a mutable list in Kotlin.
It is not permissible to modify a list while iterating over it; otherwise, ConcurrentModificationException will be thrown. However, you can use any of the following methods to safely remove elements from the list that doesn’t involve iterating it.
1. Using removeAll() function
The idea is to collect a list of elements that match the given predicate and then pass that collection to the removeAll() function. This will remove those elements from the original list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.function.Predicate fun <T> remove(list: MutableList<T>, predicate: Predicate<T>) { val newList: MutableList<T> = ArrayList() list.filter { predicate.test(it) }.forEach { newList.add(it) } list.removeAll(newList) } fun main() { var days: MutableList<String> = mutableListOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") var weekend = Predicate { day: String -> day == "Sunday" || day == "Saturday" } remove(days, weekend) println(days) // [Monday, Tuesday, Wednesday, Thursday, Friday] } |
2. Using remove() function
Since you can’t modify a list while iterating over it, you can create a filtered list of elements to be removed and then remove those elements from the original list. This can be implemented as follows using filter() and forEach() function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.function.Predicate fun <T> remove(list: MutableList<T>, predicate: Predicate<T>) { list.filter { predicate.test(it) }.forEach { list.remove(it) } } fun main() { var days: MutableList<String> = mutableListOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") var weekend = Predicate { day: String -> day == "Sunday" || day == "Saturday" } remove(days, weekend) println(days) // [Monday, Tuesday, Wednesday, Thursday, Friday] } |
3. Using removeIf() function
The simplest solution is to directly call the removeIf() function, which removes all elements from the list that satisfies the given predicate.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.function.Predicate fun <T> remove(list: MutableList<T>, predicate: Predicate<T>) { list.removeIf { x: T -> predicate.test(x) } } fun main() { var days: MutableList<String> = mutableListOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") var weekend = Predicate { day: String -> day == "Sunday" || day == "Saturday" } remove(days, weekend) println(days) // [Monday, Tuesday, Wednesday, Thursday, Friday] } |
That’s all about conditionally remove elements 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 :)