Add values at the beginning of a List in Kotlin
This article explores different ways to add values at the beginning of a List in Kotlin.
1. Using add() function
The standard solution to insert a specified element at the specified position in the list is using the add() function. It accepts the index of the element and the element to be inserted, as shown below:
|
1 2 3 4 5 6 7 8 |
fun main() { val values = mutableListOf(4, 6, 8) val item = 2 values.add(0, item) println(values) // [2, 4, 6, 8] } |
2. Using Deque
The add() function creates space for the new element at the beginning, leading to shifting all the list elements to the right (and possible re-allocation of memory). To insert the specified element at the front, consider using the ArrayDeque or LinkedList class, which implements a Deque.
|
1 2 3 4 5 6 7 8 |
fun main() { val values = ArrayDeque(listOf(4, 6, 8)) val item = 2 values.addFirst(item) println(values) // [2, 4, 6, 8] } |
3. Using plus() function
A simple solution to combine two lists in Kotlin is using the + operator. The idea is to convert the given values into a list and concatenate it with the given list using the + operator. You may also use the plus() function.
|
1 2 3 4 5 6 7 |
fun main() { var values = listOf(4, 6, 8) val item = 2 values = listOf(item) + values println(values) // [2, 4, 6, 8] } |
4. Using reverse() function
Although not recommended, you can use the reverse() function to reverse the list. Then insert the specified value at its end and reverse the list again to get the desired order.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val values = mutableListOf(4, 6, 8) val item = 2 values.reverse() values.add(item) values.reverse() println(values) // [2, 4, 6, 8] } |
That’s all about adding values at the beginning of 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 :)