Remove first element from a List in Kotlin
This article explores different ways to remove the first element from a List in Kotlin.
1. Using removeAt() function
The removeAt() function removes an element at the specified index from a mutable list. It can be called as follows:
|
1 2 3 4 5 6 |
fun main() { val nums = (1.. 5).toMutableList() nums.removeAt(0) println(nums) // [2, 3, 4, 5] } |
We should place a bound check before calling the removeAt() function, otherwise java.lang.IndexOutOfBoundsException will be thrown.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun removeFirst(nums: MutableList<Int>?) { if (nums != null && nums.size > 0) { nums.removeAt(0) } } fun main() { val nums = mutableListOf<Int>() removeFirst(nums) println(nums) // [] } |
2. Using clear() function
Another alternative is to get a view of the first element of the list and call the clear() function on it. This can be done using the subList() function, which returns a sublist that is “backed” by the original list, as shown below.
|
1 2 3 4 5 6 |
fun main() { val nums = (1.. 5).toMutableList() nums.subList(0, 1).clear() println(nums) // [2, 3, 4, 5] } |
As with the previous approach, it is safe to check for an empty list before invoking the sublist() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun removeFirst(nums: MutableList<Int>) { if (nums.isNotEmpty()) { nums.subList(0, 1).clear() } } fun main() { val nums = mutableListOf(1, 2, 3, 4, 5) removeFirst(nums) println(nums) // [2, 3, 4, 5] } |
3. Using drop() function
Both the above solutions in-place modify the list. To get a new list without touching the original list, use the drop(n) function instead. It returns a list containing all elements except the first n elements.
|
1 2 3 4 5 6 7 |
fun main() { val nums = (1.. 5).toMutableList() val c = nums.drop(1) println(c) // [2, 3, 4, 5] } |
4. Using filterIndexed() function
Finally, we can use the filterIndexed() function to remove the first element from the list. It returns a new list containing elements matching the specified predicate function, that takes the index of an element and the element itself and returns the result of predicate evaluation on the element.
|
1 2 3 4 5 6 7 |
fun main() { val nums = (1.. 5).toMutableList() val c = nums.filterIndexed { index, _ -> index > 0 } println(c) // [2, 3, 4, 5] } |
That’s all about removing the first 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 :)