Filter a list in Kotlin
This article explores different ways to filter a list in-place with Kotlin.
1. Using Iterator’s remove() function
The simple approach to filtering a MutableList in-place is to iterate through the list using an iterator and remove the list elements using iterator’s remove() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun main() { val list: MutableList<Int> = (1..10).toMutableList() val itr = list.iterator() while (itr.hasNext()) { val curr = itr.next() if (curr % 2 == 1) { // remove odd values itr.remove() } } println(list) // [2, 4, 6, 8, 10] } |
Please note that ConcurrentModificationException will be thrown if remove() function of MutableList is used instead.
2. Using retainAll() function
The recommended solution is to use the retainAll() function that only retains elements of MutableList that match with the given predicate.
|
1 2 3 4 5 6 |
fun main() { val list: MutableList<Int> = (1..10).toMutableList() list.retainAll { it % 2 == 0 } // remove odd values println(list) // [2, 4, 6, 8, 10] } |
3. Using removeAll() function
Alternatively, you can use the removeAll() function that removes elements of MutableList that match with the given predicate.
|
1 2 3 4 5 6 |
fun main() { val list: MutableList<Int> = (1..10).toMutableList() list.removeAll { it % 2 == 1 } // remove odd values println(list) // [2, 4, 6, 8, 10] } |
4. Using filter() function
If you don’t want to modify the original list or the given list is immutable, you can call the filter() function, which creates a new list containing all elements matching the given predicate.
|
1 2 3 4 5 6 |
fun main() { val list: MutableList<Int> = (1..10).toMutableList() val filteredList: List<Int> = list.filter { it % 2 == 0 } // remove odd values println(filteredList) // [2, 4, 6, 8, 10] } |
5. Using filterNot() function
Alternatively, you can use the filterNot() function, which returns a list containing all elements except the given predicate.
|
1 2 3 4 5 6 |
fun main() { val list: MutableList<Int> = (1..10).toMutableList() val filteredList: List<Int> = list.filterNot { it % 2 == 1 } // remove odd values println(filteredList) // [2, 4, 6, 8, 10] } |
That’s all about filtering 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 :)