What is list in Kotlin?

A list is a generic collection of elements. Kotlin has three Collections while List is one of those. The other two collections are Set and Map.

The List is mutable i.e. you cannot add or update the elements in the original list.

If you require to update or add new elements in a list then Kotlin provides MutableList class.

Kotlin Lists main points to note:

  • The Kotlin List<out T> is an interface.
  • Just like Java, it inherits from the Collection<T>.
  • The List<out T> provides operations like size, get, etc. that are read-only.
  • The methods for changing a list e.g add, removeAt, replaceAll, etc. are added by MutableList<T> interface.

The section below shows how to initialize and perform operations in mutable and immutable lists.

How to initialize a list in Kotlin?

The read-only list (immutable) can be created by using the listOf() method as shown below:

val a_list = listOf(“Kotlin”, “Programing”, “Language”)

You may also create a list by specifying its type:

val a_list = listOf<String>(“Kotlin”, “Programing”, “Language”)

For creating a mutable list, you may use the mutableListOf() method as follows:

val a_list = mutableListOf(“Kotlin”, “Programing”, “Language”)

Now, let us look at a few useful list methods for performing tasks like accessing elements, iterating through the list, deleting, adding and updating elements (in the case of mutable lists).

An example of creating and accessing a read-only list – the get method

In the example below, a list of five elements is created and then we accessed its elements by using the get() method.

The get() method takes an argument, which is the index in the list. Note that, the index of a list starts at zero. See how it works:

fun main(args: Array<String>) {

    val a_list = listOf(5, 10, 15, 20, 25, 30)

    println("The element at index 0: " +a_list.get(0))

    println("The element at index 2: " +a_list.get(2))

}

The output:

The element at index 0: 5

The element at index 2: 15

You may also access the elements by using double brackets []. See an example below:

fun main(args: Array<String>) {

    val a_list = listOf(5, 10, 15, 20, 25, 30)

    println("The element at index 1: " +a_list[0])

    println("The element at index 3: " +a_list[2])

}

The result:

The element at index 1: 5

The element at index 3: 15

The example of the size property

For knowing how many elements a list has, you may use the size property. The example below shows how to use it:

fun main(args: Array<String>) {

    val list_chars = listOf('a', 'b', 'f', 'g', 'k')

    println("Size of the list = " +list_chars.size)

}

The output of the above code:

Size of the list = 5

The example of min, max and avg functions of list

Again, I am using a read-only list for showing how these simple functions work.

  • The min() function returns the minimum item in the list.
  • The max() function returns the maximum item in the list.
  • While the and() function returns the average.

The example code shows the usage of all these functions with a list of numeric elements:

fun main(args: Array<String>) {

    val list_nums = listOf(100, 200, 50, 70, 300)



    println("The minmum value int the list:" +list_nums.min())

    println("Maximum value int the list:" +list_nums.max())

    println("Average:" +list_nums.average())

}

The result:

The minimum value int the list:50

Maximum value int the list:300

Average:144.0

Getting the total elements in a list by count() method

The count method returns the total number of elements in the list. In the example below, a list is created with a number of numeric items and then I used the count method to get the total number of elements:

fun main(args: Array<String>) {

    val list_chars = listOf('a', 'b', 'f', 'g', 'k')

    println("Total elements in the list by count = " +list_chars.count())

}

The result:

Total elements in the list by count = 5

The distinct function

A list may contain duplicate elements and in certain scenarios, you may require to get only the unique element in a list. For that, the distinct() function can be used. The list below contains duplicate numeric items and see distinct returns only unique elements:

The code:

fun main(args: Array<String>) {

    val list_num = listOf(100, 200, 500, 100, 300, 200, 500)



    println("The unique elements in the list: " +list_num.distinct())

}

The output:

The unique elements in the list: [100, 200, 500, 300]

Using drop and dropLast functions example

If you need to get a list with the specified number of items removed from the start or end of the list, you may use the drop and dropLast functions.

  • The drop function returns the list with elements except for the n number from the beginning.
  • The dropLast also returns a list except for the n number of elements from the last.

See the usage below:

The code:

fun main(args: Array<String>) {

    val list_num = listOf(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)



    println("List after dropping first three elements: " +list_num.drop(3))

    println("List after dropping last three elements: " +list_num.dropLast(3))

}

The result:

List after dropping first three elements: [40, 50, 60, 70, 80, 90, 100]

List after dropping last three elements: [10, 20, 30, 40, 50, 60, 70]

Getting the first and last elements example

The first() and last() are the functions that return the first and last elements for the given list, respectively. See the example code below for their usage:

Example code:

fun main(args: Array<String>) {

    val list_names = listOf<String>("Hina", "Tina", "Mina", "Mike", "Haynes")



    println("First elements in the list: " +list_names.first())

    println("Last element: " +list_names.last())

}

The output:

First elements in the list: Hina

Last element: Haynes

Performing changes in the original list – the mutable list example

In all the above examples, we used read-only lists that are immutable. Now let us look at a few examples of modifying the original list.

For creating a mutable list, we can use the mutableListOf() method and then may perform the operations like deleting an item, modifying the existing element etc.

The clear method example

The clear() function removes all elements from the list.

In the example below, I created a mutable list of numbers and then iterated through that list for displaying its elements.

This is followed by using the clear() function and we “iterated” through the list again. See the list before and after using the clear() function:

The code:

fun main(args: Array<String>) {

    val List_langs = mutableListOf("Kotlin", "Java", "Python", "C$")



    println("########List Before Clear")

    for (ele in List_langs) {

        println("$ele ")

    }

    List_langs.clear()

    println("########List After Clear")

    for (ele in List_langs) {

        println("$ele ")

    }

}

The output:

Kotlin List

Using the remove() function

If you require removing a single instance of the specified element then use the remove() function.

The remove() function is used to delete the first occurrence of the element. See an example below:

The code:

fun main(args: Array<String>) {

    val List_langs = mutableListOf("Kotlin", "Java", "Python", "C$")



    println("########List Before Remove##########")

    for (ele in List_langs) {

        println("$ele ")

    }

    List_langs.remove("Python")

    println("########List After Removing Python element##########")

    for (ele in List_langs) {

        println("$ele ")

    }

}

The output:

########List Before Remove##########

Kotlin

Java

Python

C$

########List After Removing Python element##########

Kotlin

Java

C$

You can see, the element “Python” is removed from the list.

The removeAt() function example

Want to remove an item by index? Use the removeAt() function. It takes a parameter which is the index of the element that you intend to remove. Have a look:

The example code:

fun main(args: Array<String>) {

    val List_nums = mutableListOf(5, 50, 500, 5000, 50000)



    println("########List Before RemoveAt##########")

    for (i in 0 until List_nums.size) {



        println("${List_nums[i]} ")

    }



    List_nums.removeAt(2)

    println("########List After RemoveAt##########")

    for (i in 0 until List_nums.size) {



        println("${List_nums[i]} ")

    }

}

 

The output:

########List Before RemoveAt##########

5

50

500

5000

50000

########List After RemoveAt##########

5

50

5000

50000

The second element which value is 500 is removed from the list.

Adding an element example – the add() function

The add() function adds the specified element at the end of the list. You may also add an element at the specified position if the second argument is given.

See a demo below for both cases:

fun main(args: Array<String>) {

    val List_subjects = mutableListOf("Phy", "Che", "Bio", "Math")



    println("########List Before add function##########")

    for (i in 0 until List_subjects.size) {



        println("${List_subjects[i]} ")

    }



    List_subjects.add("History")

    println("########List After add function##########")

    for (i in 0 until List_subjects.size) {



        println("${List_subjects[i]} ")

    }

}

The list before and after:

Kotlin List add

Adding element at the specified position example

fun main(args: Array<String>) {

    val List_subjects = mutableListOf("Phy", "Che", "Bio", "Math")



    println("########List Before add function##########")

    for (i in 0 until List_subjects.size) {



        println("${List_subjects[i]} ")

    }



    List_subjects.add(2, "Zoology")

    List_subjects.add(4, "Social Studies")

    println("########List After add function##########")

    for (i in 0 until List_subjects.size) {



        println("${List_subjects[i]} ")

    }

}

The output:

########List Before add function##########

Phy

Che

Bio

Math

########List After add function##########

Phy

Che

Zoology

Bio

Social Studies

Math

Adding multiple elements – the addAll() function

The addAll() function adds multiple elements at the end of the list.

Just like add() function, you may also provide the second argument for specifying the position of newly added elements. See the code and output below:

fun main(args: Array<String>) {

    val list_num = mutableListOf(1,2,3,4,5,6)



    println("########List Before addAll function##########")

    for (i in 0 until list_num.size) {



        println("${list_num[i]} ")

    }



    list_num.addAll(listOf(7,8,9,10))



    println("########List After addAll function##########")

    for (i in 0 until list_num.size) {



        println("${list_num[i]} ")

    }

}

The result:

########List Before addAll function##########

1

2

3

4

5

6

########List After addAll function##########

1

2

3

4

5

6

7

8

9

10

A shuffle function example

For randomly re-arranging the elements in a list, you may use the shuffle() function. Be careful as using this function because it changes the original list.

The demo code:

fun main(args: Array<String>) {

    val list_num = mutableListOf(1,2,3,4,5,6)



    println("Before :" +list_num)



        list_num.shuffle()

    println("After shuffle: " +list_num)

}

The output as I executed this code:

Before :[1, 2, 3, 4, 5, 6]

After shuffle: [2, 3, 1, 4, 6, 5]

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!