1. Introduction
An array is a commonly used data structure to store a collection of elements. Occasionally, we may find the need to remove the first element from an array.
Unfortunately, we cannot directly remove elements from an array because we cannot resize them. In this tutorial, we’ll explore various methods to achieve this task, with JUnit test examples.
2. Creating a New Array Using sliceArray()
Let’s start with one of the few ways to remove the first element that still directly returns an Array. We can create a new Array containing all elements except the first one by using the sliceArray() method:
@Test
fun `Remove first element by creating a slice`() {
val array = arrayOf("Apple", "Banana", "Cherry")
val updatedArray = array.sliceArray(1 until array.size)
assertEquals(arrayOf("Banana", "Cherry"), updatedArray)
}
In fact, by using sliceArray() with the range starting at 1, we’re able to exclude the first item in the original Array from our new Array. It’s important to note that updatedArray and array aren’t linked, so changes to one won’t affect the other.
3. Creating a New Array Using drop()
The next ways we’ll look at don’t directly return Array, so we’ll make sure to convert the returned List back to an Array.
The drop() function removes the first n elements from an Array. Therefore, we can use it to remove the first element of our Array by dropping a single element:
@Test
fun `Remove first element by using drop`() {
val array = arrayOf("Apple", "Banana", "Cherry")
val updatedArray = array.drop(1).toTypedArray()
assertEquals(arrayOf("Banana", "Cherry"), updatedArray)
}
The drop() function removes n elements from the start of the array. Specifically, dropping a single item this way effectively removes the first item from the array.
Kotlin APIs on Array frequently return a List, so we use toTypedArray() to go back to an Array.
4. Using filterIndexed()
Finally, let’s use the filterIndexed() function to create a new Array with elements that satisfy a certain condition. To remove the first element, we can use the index parameter to exclude it:
@Test
fun `Remove first element by using filterIndexed`() {
val array = arrayOf("Apple", "Banana", "Cherry")
val updatedArray = array.filterIndexed { index, _ -> index != 0 }.toTypedArray()
assertEquals(arrayOf("Banana", "Cherry"), updatedArray)
}
5. Conclusion
In this article, we’ve explored various methods to remove the first element from an Array in Kotlin and saw how they work with JUnit tests.
As always, the code used in this article is available over on GitHub.