Remove slice from a list in Kotlin
This article explores different ways to remove a slice from a list between two specified indexes in Kotlin.
1. Custom Routine
The idea is to iterate backward in the list and remove all elements within the specified range.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun <T> removeSlice(list: MutableList<T>, from: Int, end: Int) { for (i in end downTo from) { list.removeAt(i) } } fun main() { val list: MutableList<Int> = (1..8).toMutableList() val start = 2 val end = 4 removeSlice(list, start, end) println(list) // [1, 2, 6, 7, 8] } |
Note that advancing in a list and removing elements from it might cause it to skip a few elements and give unexpected results.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun <T> removeSlice(list: MutableList<T>, from: Int, end: Int) { for (i in from..end) { list.removeAt(i) } } fun main() { val list: MutableList<Int> = (1..8).toMutableList() val start = 2 val end = 4 removeSlice(list, start, end) println(list) // [1, 2, 4, 6, 8] } |
2. Using clear() function
Another good solution is to use the clear() function along with the subList() function to remove a specific range from a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> removeSlice(list: MutableList<T>, from: Int, end: Int) { list.subList(from, end + 1).clear() } fun main() { val list: MutableList<Int> = (1..8).toMutableList() val start = 2 val end = 4 removeSlice(list, start, end) println(list) // [1, 2, 6, 7, 8] } |
3. Using removeAll() function
The removeAll() function removes all elements in the list that are contained in the specified collection. You can pass a sublist returned by subList() function to removeAll() function to remove them.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> removeSlice(list: MutableList<T>, from: Int, end: Int) { list.removeAll(list.subList(from, end + 1)) } fun main() { val list: MutableList<Int> = (1..8).toMutableList() val start = 2 val end = 4 removeSlice(list, start, end) println(list) // [1, 2, 6, 7, 8] } |
The slice() function can also be used instead of subList().
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> removeSlice(list: MutableList<T>, from: Int, end: Int) { list.removeAll(list.slice(from..end)) } fun main() { val list: MutableList<Int> = (1..8).toMutableList() val start = 2 val end = 4 removeSlice(list, start, end) println(list) // [1, 2, 6, 7, 8] } |
That’s all about removing a slice 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 :)