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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

 

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:

The list before and after:

Kotlin List add

Adding element at the specified position example

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:

The result:

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:

The output as I executed this code:

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

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