Code Mastery Guides

Your Journey to Mastering Programming Languages: Where Knowledge Meets Code

How to Add Element to List in Android Kotlin

Kotlin, a modern programming language designed to be brief, informative, and interoperable with existing Java code, has gained popularity for its versatility and simplicity. One common task in programming is managing lists and collections. In this article, we’ll explore how to add components to a list in Kotlin.

Image Credit: Android Developer Website

Add element into Mutable List

In Kotlin, lists are immutable by default, meaning their size and elements cannot be changed after initialization. To work with mutable lists, we typically use the MutableList interface. Let’s start by creating a simple mutable list:

val numberElements = mutableListOf(1, 2, 3, 4, 5)

Now let’s start adding elements in various ways:

Adding Single Element

To insert a single element to the list, utilize the ‘add' function as demonstrated below.

numberElements.add(6) //This code will insert the number 6 at the 5th position.

Adding Multiple Elements

To insert multiple elements in the list, leverage the addAll method by providing a list as the parameter.

numberElements.addAll(listOf(7,8,9)) 
// This code will simultaneously insert the numbers 7, 8, and 9 to the end of the list.

Adding Element at a specific position

To insert an element at a specific position in the list, employ the method provided below:

numberElements.add(5, 10) 
    /* This code will insert the number 10 at the 5th position of the list. Keep in mind that list positions start   
     from 0.*/

Adding Element by Plus Operator

This is an easier way to insert an element into a list using the plus operator.

numberElements += 10 
// This code will add '10' into list.

This code will insert 10 into the list at the last position.

Adding an element to a previously utilized list

Now, if you wish to insert an element to a list you’ve used before, simply follow these guidelines:

        val numbers = listOf(1,2,3)

        //this is previous list
        val mutableNumbers = numbers.toMutableList()

        //we convert old list into mutable list
        mutableNumbers.add(3, 4)
        // insert element into new mutable list at 3rd position

In the example above, we create a list called ‘numbers.’ Now, to add an element to it, we convert the ‘numbers’ list into a mutable list named ‘mutableNumbers’ using the toMutableList() method in the second line of code. Finally, in the third line, we add an element at a specific location in the ‘mutableNumbers’ list.

Click Here to read more articles about Android Kotlin.

To learn more about List in Android Kotlin, click here for details

How to Add Element to List in Android Kotlin

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top