Add an item at end of a List in Kotlin
This article explores different ways to add an item at the end of a mutable list in Kotlin.
1. Using add() function
A simple solution to add elements to a list is using the add() function. It is available only for a mutable list and can be used as follows to add an item at the end of a list:
|
1 2 3 4 5 6 7 |
fun main() { val nums = mutableListOf(1, 2, 3, 4) val elem = 5 nums.add(elem) println(nums) // [1, 2, 3, 4, 5] } |
The add() function optionally takes the index where the specified element needs to be inserted. To insert an item at the end, use the index equal to the list’s size.
|
1 2 3 4 5 6 7 |
fun main() { val nums = mutableListOf(1, 2, 3, 4) val elem = 5 nums.add(nums.size, elem) println(nums) // [1, 2, 3, 4, 5] } |
2. Using addAll() function
To append multiple items to the end of a list, use the addAll() function which accepts a collection. A typical invocation for this function would look like:
|
1 2 3 4 5 6 7 |
fun main() { val nums = mutableListOf(1, 2, 3, 4) val collection = listOf(5, 6, 7) nums.addAll(collection) println(nums) // [1, 2, 3, 4, 5, 6, 7] } |
3. Using Deque
We can insert an item at the end (and at the front) of a Deque in constant time. Any standard Deque implementation functionality to add the specified element at the end of a Deque. In Kotlin, we have the addLast() function.
|
1 2 3 4 5 6 7 |
fun main() { val nums = ArrayDeque(listOf(1, 2, 3, 4)) val elem = 5 nums.addLast(elem) // or add() function println(nums) // [1, 2, 3, 4, 5] } |
4. Using + operator
The idiomatic way to add an item at the end of a list is using the + operator. To illustrate, the following code creates a new list, which is the concatenation of the original list with a single item or a collection. We can use the plus() function as well.
|
1 2 3 4 5 6 7 |
fun main() { val nums = listOf(1, 2, 3, 4) val elem = 5 val newList = nums + elem println(newList) // [1, 2, 3, 4, 5] } |
That’s all about adding an item at the end 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 :)