Kotlin List

Kotlin List stores elements in a specified order and provides indexed access to them. Indices start from zero – the index of the first element – and go to lastIndex which is the (list.size - 1).

Key points of the List:
  • Methods in the List interface support only read-only access to the list; read/write access is supported through the MutableList interface.
  • Kotlin distinguishes between read-only and mutable lists. Read-only lists are created with the listOf() method and mutable lists with the mutableListOf() method.
  • In Kotlin, the default implementation of List is ArrayList which you can think of as a resizable array.
  • MutableList is a List with list-specific write operations, for example, to add or remove an element at a specific position.

Let's demonstrate the usage of important List interface methods with an example.

Kotlin listOf()

The example creates a new list of words with listOf(). The size of the list is determined by the size attribute.
package net.sourcecodeexamples.kotlin

fun main() {
    val words = listOf("Ab", "cup", "dog", "spectacles")
    println("The list contains ${words.size} elements.")
}
Output:
The list contains 4 elements.

Kotlin listOf() and mutableListOf() Example

We can create a simple read-only List using method listOf() and read-write MutableList using mutableListOf():
package net.sourcecodeexamples.kotlin

fun main() {
    val theList = listOf("one", "two", "three")
    println(theList)
    val theMutableList = mutableListOf("one", "two", "three")
    println(theMutableList)
}
Output:
[one, two, three]
[one, two, three]

Kotlin List Basic Examples

The example creates a list of numbers and computes some statistics.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = listOf(1, 15, 13, 8, 1, 19, 6, 12)

    val len = nums.count()
    val max = nums.max()
    val min = nums.min()
    val sum = nums.sum()
    val avg = nums.average()

    val msg = """
               max: $max, min: $min,
               count: $len, sum: $sum,
               average: $avg
              """
    println(msg.trimIndent())

}
Output:
max: 19, min: 1,
count: 8, sum: 75,
average: 9.375

Kotlin List Indexing

Each element of a list has an index. Kotlin list indexes start from zero. The last element has a len-1 index.

The example presents Kotlin List indexing operations.
fun main() {

    val words = listOf("pen", "cup", "dog", "person",
            "cement", "coal", "spectacles", "cup", "bread")

    val w1 = words.get(0)
    println(w1)

    val w2 = words[0]
    println(w2)

    val i1 = words.indexOf("cup")
    println("The first index of cup is $i1")

    val i2 = words.lastIndexOf("cup")
    println("The last index of cup is $i2")

    val i3 = words.lastIndex
    println("The last index of the list is $i3")
}
Output:
pen
pen
The first index of cup is 1
The last index of cup is 7
The last index of the list is 8
This is the output.

Kotlin List count

The count() method returns the number of elements in the list.

The example returns the number of values in the list, the number of negative values, and the number of even values.
package net.sourcecodeexamples

fun main() {

    val nums = listOf(12, 1,2,5,4,2)

    val len = nums.count()
    println("There are $len elements")
    
    val size = nums.size
    println("The size of the list is $size")    

    val n1 = nums.count { e -> e < 0 }
    println("There are $n1 negative values")

    val n2 = nums.count { e -> e % 2 == 0 }
    println("There are $n2 even values")
}
Output:
There are 6 elements
The size of the list is 6
There are 0 negative values
There are 4 even values

Kotlin List first and last elements

The following example creates a list of fruits. We get the first and the last elements of the list.
package net.sourcecodeexamples.kotlin

fun main() {

    val fruits = listOf("banana", "mango", "apple", "orange")

    val w1 = fruits.first()
    println(w1)

    val w2 = fruits.last()
    println(w2)

    val w3 = fruits.findLast { w -> w.startsWith('a') }
    println(w3)

    val w4 = fruits.first { w -> w.startsWith('o') }
    println(w4)
}
Output:
banana
orange
apple
orange
We get the first element with the first():
val w1 = words.first()
We get the last element with the last():
val w2 = words.last()
We retrieve the last element of the list that starts with 'a' with findLast():
val w3 = words.findLast { w -> w.startsWith('a') }
We retrieve the first element of the list that starts with 'o' with first():
val w4 = words.first { w -> w.startsWith('o') }

Kotlin List iterate

Here are five ways of looping over a list in Kotlin.

  1. Using forEach() method
  2. Using for loop
  3. An alternative for cycle utilizes the size of the list
  4. Using forEachIndexed() method
  5. Using a ListIterator and a while loop
Here is a complete source code to demonstrate five ways of looping over a list inKotlin.
package net.sourcecodeexamples.kotlin


fun main() {

     val fruits = listOf("banana", "mango", "apple", "orange")

      // using forEach() method
     fruits.forEach { e -> print("$e ") }
     println()

     // using for loop
     for (fruit in fruits) {
          print("$fruit ")
     }

     println()

     // An alternative for cycle utilizes the size of the list
     for (i in 0 until fruits.size) {
          print("${fruits[i]} ")
     }

     println()

     // using forEachIndexed() method
     fruits.forEachIndexed({ i, e -> println("fruits[$i] = $e") })

     // using a ListIterator and a while loop
     val it: ListIterator<String> = fruits.listIterator()

     while (it.hasNext()) {
           val e = it.next()
           print("$e ")
     }

     println()
}

Output

banana mango apple orange 
banana mango apple orange 
banana mango apple orange 
fruits[0] = banana
fruits[1] = mango
fruits[2] = apple
fruits[3] = orange
banana mango apple orange 

Kotlin List Sort - Ascending and Descending Order

The example sorts list values in ascending and descending order, and reverses list elements.
package net.sourcecodeexamples.kotlin

fun main() {

 val nums = listOf(10, 5, 3, 4, 2, 1, 11, 14, 12)

 val sortAsc = nums.sorted()
 println("sortAsc -> " + sortAsc)

 val sortDesc = nums.sortedDescending()
 println("sortDesc -> " + sortDesc)

 val revNums = nums.reversed()
 println("revNums -> " + revNums)
}
Output:
sortAsc -> [1, 2, 3, 4, 5, 10, 11, 12, 14]
sortDesc -> [14, 12, 11, 10, 5, 4, 3, 2, 1]
revNums -> [12, 14, 11, 1, 2, 4, 3, 5, 10]

Kotlin List contains()

This example shows how to use contains() method to check if a list contains the specified elements.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = listOf(1, 2, 3, 7, 6, 5, 4)

    val r = nums.contains(4)

    if (r) {
        println("The list contains 4")
    } else {
        println("The list does not contain 4")
    }
    val r2 = nums.containsAll(listOf(1, 6))

    if (r2) {
        println("The list contains 1 and 6")
    } else {
        println("The list does not contain 1 and 6")
    }
}
Output:
The list contains 4
The list contains 1 and 6

Kotlin List contains()

A slice is a portion of a list. Slices can be created with the slice() method. The method takes indexes of the elements to be picked up.

In the example, we create a list of integers. From the list, we produce two slices.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = listOf(1, 2, 3, 4, 5, 6)

    val nums2 = nums.slice(1..3)
    println(nums2)

    val nums3 = nums.slice(listOf(3, 4, 5))
    println(nums3)
}
Output:
[2, 3, 4]
[4, 5, 6]

Kotlin List Filter Example

Kotlin List filter Filtering is an operation where only elements that meet certain criteria pass through.

The following example presents the filtering operation on Kotlin lists.
package net.sourcecodeexamples.kotlin

fun main(args: Array<String>) {

    val fruits = listOf("banana", "mango", "apple", "orange")

    val fruits1 = fruits.filter { e -> e.length == 5 }
    fruits1.forEach { e -> print("$e ") }

    println()

    val fruits2 = fruits.filterNot { e -> e.length == 5 }

    fruits2.forEach { e -> print("$e ") }
    println()
}
Output:
mango apple 
banana orange 

Kotlin List any

The any() method returns true if at least one element matches the given predicate function.

The following example shows the usage of any() method in Kotlin.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = listOf(1,2,3,4,5,6,7,-1,-2)

    val r = nums.any { e -> e > 10 }
    if (r) {
        println("There is a value greater than ten")
    } else {
        println("There is no value greater than ten")
    }

    val r2 = nums.any { e -> e < 0 }

    if (r2) {
        println("There is a negative value")
    } else {
        println("There is no negative value")
    }
}

Output:
There is no value greater than ten
There is a negative value

Kotlin List all

The all() returns true if all elements satisfy the given predicate function.

The following example shows the usage of all() methods in Kotlin.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
    val nums2 = listOf(-3, -4, -2, -5, -7, -8)

    // testing for positive only values
    val r = nums.all {
        e - > e > 0
    }

    if (r) {
        println("nums list contains only positive values")
    } else {
        println("nums list does not contain only positive values")
    }


    // testing for negative only values
    val r2 = nums2.all {
        e - > e < 0
    }

    if (r2) {
        println("nums2 list contains only negative values")
    } else {
        println("nums2 list does not contain only negative values")
    }
}
Output:
nums list contains only positive values
nums2 list contains only negative values

Kotlin List drop

With the drop operations, we exclude some elements from the list.

The example shows the usage of different drop operations.
package net.sourcecodeexamples.kotlin

fun main() {

    val nums = listOf(1,2,-1,-2,3,4,5,6,7,8,9,10)

    val nums2 = nums.drop(3)
    println(nums2)

    val nums3 = nums.dropLast(3)
    println(nums3)

    val nums4 = nums.sorted().dropWhile { e -> e < 0 }
    println(nums4)

    val nums5 = nums.sorted().dropLastWhile { e -> e > 0 }
    println(nums5)
}
Output:
[-2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, -1, -2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[-2, -1]

Conclusion

That’s all folks. In this tutorial, we have covered Kotlin lists with examples. The source code of this tutorial is available on my Github repository at https://github.com/RameshMF/kotlin-tutorial.

Thank you for reading. See you in the next post.

References

The source code of this tutorial is available on my GitHub Repository.

Comments