Kotlin List and MutableList Collections Tutorial

In this section, we will learn what the List and MutableList are and how to use them in Kotlin.

What is List Collection in Kotlin?

The List Interface is a type of Interface that we used to create a collection type object where we can store multiple values (objects) in it.

The work of a List object is almost the same as an array except it has multiple useful functions that we can use for a different type of purpose.

Note: just like arrays, an object of type List is immutable! Meaning, after setting the elements of a list object, you can’t increase or decrease its elements.

How to create a List object in Kotlin? Kotlin listOf() Function:

In order to create an object of type List, we use a function named `listOf()`.

Simply call this function and pass the elements you want the new List object to hold as the argument of the function.

Note: the data type of elements that we pass to this function could be of any type (if the type of the variable that is going to hold a reference of the new list object is set to be automatically inferred of course or we’ve explicitly set the type to be List<Any>).

The List interface is a generic one and it has a generic type name. So we can use that and set a specific type if we want to make sure all the elements we set as the argument of the function have the same data type.

For example:

var variableName: List<Int> = ListOf(1,2,3,4,5,6)

Here, if we try to put values of different type (other than Int) we will get a compile time error.

Example: creating a List object in Kotlin using listOf() Function:

fun main(){
    var names = listOf("Jack","Ellen","John","Omid")

    for (element in names){
        println(element)
    }
}

Output:

Jack

Ellen

John

Omid

How to Access Elements of a List Object?

There are multiple ways to access the elements of a list object!

One of them that we’ve seen in the last example is by running a for loop on the target list collection. The for loop is smart enough to loop through the elements of a collection and return them one by one.

The other method of accessing the elements of the List collection is by using the index number associated with each element in the list and the get() function.

Basically, just like arrays, list also has index numbers. For example, the first element of a list lives in the first index of the list, the second one is in the index number 1 and so on…

Now, by passing the index number of the element that we want to access as the argument of the get() function, we can easily get the value in that index number.

Also, you can use a pair of brackets after the name of a List object and pass an index number into it in order to get the value in that index. (The use of brackets is exactly the same as the way we use them to access the elements of an array)

Example: accessing the elements of a list object

fun main(){
    var names = listOf("Jack",10,"John","Omid")
    println(names.get(0))
    println(names.get(1))
    println(names[2])
}

Output:

Jack

10

John

Note: If you try to put an index number beyond the range of a List object, you’ll get a runtime exception.

Kotlin List contains() Function

The contains() function belongs to the List, and it checks to see if a specific value exists in a List object or not.

For example, if you want to know if a List object has a value like “John” as part of its elements, you can pass this value as the argument of the function and it will return a Boolean value as a result.

If the value was true, that means the list has the specified value. Otherwise, the value false will return instead.

Example: using List contains() function in Kotlin

fun main(){
    var names = listOf("Jack",10,"John","Omid")
    println(names.contains("Jack"))
    println(names.contains("Ellen"))
    
}

Output:

true

false

Kotlin List indexOf() Function

The indexOf() function takes a value as its argument, checks the target list object to find the specified value and if found one, it’ll return the index number of that value.

Otherwise, if the specified value wasn’t in the target list object, then the result will be -1.

Example: using List indexOf() function in Kotlin

fun main(){
    var names = listOf("Jack",10,"John","Omid")
    var res = names.indexOf("John")
    println("The index number of the value John is: $res")
}

Output:

The index number of the value John is: 2

What is MutableList Collection in Kotlin?

The MutableList collection is also like the List collection that we’ve explained so far with one key difference:

While a List object cannot change its value, an object of type MutableList can dynamically increase or decrease the number of elements it currently has!

Basically, if you start off with 3 elements, for example, then at runtime you can easily increase this number by adding more values to the collection.

Note: A MutableList object and a List object both are from the same family and so every function and methods we’ve seen so far that worked for the List objects, work for a MutableList as well.

How to create a MutableList object in Kotlin? Kotlin mutableListOf() Function:

In order to create an object of type MutableList, we call the mutableListOf() function.

The function takes one or more elements as its arguments.

But again, remember that you’re not limited to the specified values of this function and you can easily increase the elements of a MutableList object at runtime.

Example: creating a MutableList object in Kotlin using mutableListOf() function

fun main(){
    var names = mutableListOf("Jack",10,"John","Omid")
    var colors = mutableListOf(1)
    println("The size of the names collection is: ${names.size}")
    println("The size of the colors collection is: ${colors.size}")

}

Output:

The size of the names collection is: 4

The size of the colors collection is: 1

Kotlin MutableList Object Adding Element

In order to add new elements to a MutableList object, we can use the add() function.

Simply pass a value as the argument of this function and that will be added as the last element of a MutableList object.

Note: the add() function has two forms!

The first form takes only one argument and adds that argument as the last element of the collection.

The second form takes two arguments however:

  • The first argument is the index number where we want to insert the new element.
  • The second argument is the value itself that we want to insert into the collection.

Note: if there is an element already set in the specified index number, that value and any other value afterward will be pushed one level to the end of the collection so that the new element could be added to the collection.

Example: adding elements to a MutableList object using add() function

fun main(){
    var names = mutableListOf("Jack",10,"John","Omid")
    
    println("The elements of the names collection before calling the add() function:")
    println(names.toString())

    names.add("Elon")
    names.add("Monica")
    println("The elements of the names collection after calling the add() function: ")
    println(names.toString())
}

Output:

The elements of the names collection before calling the add() function:

[Jack, 10, John, Omid]

The elements of the names collection after calling the add() function:

[Jack, 10, John, Omid, Elon, Monica]

Example: inserting elements to a MutableList object using add() function

fun main(){
    var names = mutableListOf("Jack",10,"John","Omid")
    
    println("The elements of the names collection before calling the add() function:")
    println(names.toString())

    names.add(1,"Elon")
    names.add(0,"Monica")
    println("The elements of the names collection after calling the add() function: ")
    println(names.toString())
}

Output:

The elements of the names collection before calling the add() function:

[Jack, 10, John, Omid]

The elements of the names collection after calling the add() function:

[Monica, Jack, Elon, 10, John, Omid]

Kotlin MutableList Object: Replacing a value with another one using the set() function

Now if you have an element already in a MutableList collection and want to replace that with another value, you can use the set() function.

This function takes two arguments:

  • The first argument is the index number where we want to replace a value there.
  • The second argument is the actual value that wants to send to the specified index number.

Note that this function returns the old value in the specified index as the result of calling the function.

Example: using the set() function to replace a value in a MutableList with another one

fun main(){
    var names = mutableListOf("Jack",10,"John","Omid")
    
    println("The elements of the names collection before calling the set() function:")
    println(names.toString())

    names.set(1,"Elon")
    names.set(0,"Monica")
    println("The elements of the names collection after calling the set() function: ")
    println(names.toString())
}

Output:

The elements of the names collection before calling the set() function:

[Jack, 10, John, Omid]

The elements of the names collection after calling the set() function:

[Monica, Elon, John, Omid]

Kotlin MutableList Object: Removing Elements using remove() Function

Using the remove() function, we can remove an element from a MutableList object.

The function takes one argument, and that is the value that we want to remove from the target collection.

Note that this function looks into the target collection and only removes the first occurrence of the value and not the entire occurrences!

This function, on a successful operation, will return the value true (meaning the target value was removed from the list). Otherwise, the value false will return instead (for example, because the value was not in the target list).

Example: removing elements from a MutableList object using the remove() function

fun main(){
    var names = mutableListOf("Jack",10,"John","Omid")

    println("The elements of the names collection is: ")
    println(names.toString())

    names.remove("Jack")
    names.remove(10)
    println("The elements of the names collection after calling the remove() function")
    println(names.toString())
}

Output:

The elements of the names collection is:

[Jack, 10, John, Omid]

The elements of the names collection after calling the remove() function

[John, Omid]

Kotlin MutableList Object: Shuffling Elements using shuffle() Function

The elements we put in a MutableList have order! For example, the first value we put in a list will always have the index number 0 and we can use this index number to access the value.

But there’s a function named shuffle() by which we can shuffle the elements and set a new position for each element on the list.

Example: shuffling a MutableList object using shuffle() function

fun main(){
    var names = mutableListOf("Jack",10,"John","Omid")

    println("The elements of the names collection is: ")
    println(names.toString())

    names.shuffle() 
    println("The elements of the names collection after calling the shuffle() function")
    println(names.toString())
}

Output:

The elements of the names collection is:

[Jack, 10, John, Omid]

The elements of the names collection after calling the shuffle() function

[John, Jack, Omid, 10]
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies