Prepend an element to a list in Kotlin
This article explores different ways to prepend an element to a list in Kotlin. In other words, insert an element at the front of the list.
1. Using add() function
The standard solution to prepend an element to the front of a list, you can use the add() function with the specified index as 0.
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> MutableList<T>.prepend(element: T) { add(0, element) } fun main() { var list = mutableListOf(2, 3, 4, 5) list.prepend(1) println(list) // [1, 2, 3, 4, 5] } |
You can easily extend the solution to add multiple elements to the front of the list.
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> MutableList<T>.prependAll(elements: List<T>) { addAll(0, elements) } fun main() { var list = mutableListOf(3, 4, 5) list.prependAll(listOf(1, 2)) println(list) // [1, 2, 3, 4, 5] } |
2. Using LinkedList‘s push() function
If you’re using Doubly linked list implementation of the List and Deque interfaces, say a LinkedList, you can easily prepend elements to it with native push() function. This is demonstrated below:
|
1 2 3 4 5 6 7 8 |
import java.util.LinkedList fun main() { val list = LinkedList(listOf(2, 3, 4, 5)) list.push(1) println(list) // [1, 2, 3, 4, 5] } |
This function is equivalent to the addFirst() function.
|
1 2 3 4 5 6 7 8 |
import java.util.LinkedList fun main() { val list = LinkedList(listOf(2, 3, 4, 5)) list.addFirst(1) println(list) // [1, 2, 3, 4, 5] } |
3. Using + operator
Another solution is to wrap the given element in a list and then use the + operator to concatenate the new list with the original list.
|
1 2 3 4 5 6 |
fun main() { var list = listOf(2, 3, 4, 5) list = listOf(1) + list println(list) // [1, 2, 3, 4, 5] } |
The + operator is equivalent to the plus() function shown below:
|
1 2 3 4 5 6 |
fun main() { var list = listOf(2, 3, 4, 5) list = listOf(1).plus(list) println(list) // [1, 2, 3, 4, 5] } |
That’s all about prepending an element to 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 :)