In this tutorial, we will talk about Kotlin List with the help of simple examples.
List
- An ordered collection of elements.
- The ordered is maintained through indices (same as arrays). Indices start from zero(the index of the first element) and go to lastIndex which is the (list.size – 1).
- An element (including null) can occur more than one time in a list.
- Lists are of two types, immutable lists (cannot be modified) and mutable lists (can be modified).
Kotlin Immutable List
The immutable list also known as read-only lists support only read-only access to the list.
Immutable lists are created using listOf() and listOf<T>() functions.
Create and initialize list with values
The below example show you how to:
- initialize List using listOf() (contains elements of all type), listOf<T>() (contains elements of specific type) and listOfNotNull() (contains no null element) functions.
- create new List from another List with the same elements using toList() function.
fun main() {
var list1 = listOf("Arun", 10, 1.05f, 'a', null, 10)
var list2 = listOfNotNull("Arun", null, 10, null, 10)
var nameList1 = listOf<String>("Arun", "Neha", "Monika")
val nameList2 = nameList1.toList()
println("list1: $list1")
//list1: [Arun, 10, 1.05, a, null, 10]
println("list2: $list2")
//list2: [Arun, 10, 10]
println("nameList1: $nameList1")
//nameList1: [Arun, Neha, Monika]
println("nameList2: $nameList2")
//nameList2: [Arun, Neha, Monika]
}
Access items from List
The below example show you how to:
- find the size of a List using size property or count() method.
- get the index of last element using lastIndex and the IntRange for list using Indices.
- check if a List is empty or not using isEmpty() or isNotEmpty().
- access the item at specified index in a List using operator [], get(), getOrElse(), getOrNull()
val num1 = listOf<Int>(1, 2, 3, 4, 5, 6)
// Properties
println("List size: ${num1.size}")
//List size : 6
println("Last element index: ${num1.lastIndex}")
//Last element index: 5
println("IntRange for list: ${num1.indices}")
//IntRange for list: 0..5
// Functions
println("List size using count(): ${num1.count()}")
//List size using count (): 6
println("Is list empty: ${num1.isEmpty()}")
//Is list empty: false
println("Is list not empty: ${num1.isNotEmpty()}")
//Is list not empty : true
println("Element at index 2: ${num1.get(2)}") //Element at index 2: 3
println("Element at index 3: ${num1[3]}") //Element at index 3: 4
println("Element at index 3 or '-1' if index is out of bounds: ${num1.getOrElse(3, { -1 })}")
//Element at index 3 or '-1' if index is out of bounds: 4
println("Element at index 6 or 'null' if index is out of bounds: ${num1.getOrNull(6)}")
//Element at index 6 or 'null' if index is out of bounds: null
Get subList of a List
The below example show you how to:
- get subList of the List from specified index to another index (exclusive) using subList() method.
- get subList of the List by specifying the range using slice() method.
val num1 = listOf<Int>(1, 2, 3, 4, 5, 6)
println("Sublist from index 1 to 3: (exclusive) ${num1.subList(1, 3)}")
//Sublist from index 1 to 3(exclusive): [2, 3]
println("Sublist using intRange 1..3: ${num1.slice(1..3)}")
//Sublist using intRange 1..3: [2, 3, 4]
Take List elements
The below example show you how to:
- take the first or last items of a List using take() or takeLast() function.
- take the first items of a List satisfying the given condition using takeWhile() function.
- take the last items of a List satisfying the given condition using takeLastWhile() function.
val num1 = listOf<Int>(1, 2, 3, 4, 5, 6)
println("First three elements of a list: ${num1.take(3)}")
//First three elements of a list: [1, 2, 3]
println("First items of a List satisfying the condition: ${num1.takeWhile { it < 5 }}")
//First items of a List satisfying the condition: [1, 2, 3, 4]
println("Last three elements of a list: ${num1.takeLast(3)}")
//Last three elements of a list: [4, 5, 6]
println("Last items of a List satisfying the condition: ${num1.takeLastWhile { it > 4 }}")
//Last items of a List satisfying the condition: [5, 6]
Drop List elements
The below example show you how to:
- get subList that contains all items by dropping first items or last items using drop() or dropLast()
- get subList containing all items by dropping first items that satisfy a given condition using dropWhile()
- get subList containing all items by dropping last items that satisfy a given condition using dropLastWhile()
val num1 = listOf<Int>(1, 2, 3, 4, 5, 6)
println("Drop first three elements of a list: ${num1.drop(3)}")
//Drop first three elements of a list: [4, 5, 6]
println("Drop first elements of a List satisfying the condition: ${num1.dropWhile { it < 5 }}")
//Drop first elements of a List satisfying the condition: [5, 6]
println("Drop last two elements of a list: ${num1.dropLast(2)}")
//Drop last two elements of a list: [1, 2, 3, 4]
println("Drop last elements of a List satisfying the condition: ${num1.dropLastWhile { it > 4 }}")
//Drop last elements of a List satisfying the condition: [1, 2, 3, 4]
Find elements in List
The below example show how to:
- find the index of the first/last occurrence of an element using indexOf() / lastIndexOf()
- find the first/last element of the list using first()/last()
- check if a List contains an element or not using contains()
- check if a List contains all given elements or not using containsAll()
- find the index of the first/last occurrence of an element that matches a condition using indexOfFirst() / indexOfLast()
- find the first/last element in the list that matches a condition using find() / findLast()
val num2 = listOf<Int>(2, 3, 4, 5)
val num3 = listOf<Int>(1, 2, 3, 4, 3, 5, 1, 6)
val strList = listOf<String>("book", "cook", "took", "look")
println("Element(3) first occurrence index: ${num3.indexOf(3)}")
//Element(3) first occurrence index: 2
println("Element(1) last occurrence index: ${num3.lastIndexOf(1)}")
//Element(1) last occurrence index: 6
println("First element in list: ${num3.first()}")
//First element in list: 1
println("Last element in list: ${num3.last()}")
//Last element in list: 6
println("Does 3 exist in list: ${num3.contains(3)}")
//Does 3 exist in list: true
println("Does 9 exist in list: ${num3.contains(9)}")
//Does 9 exist in list: false
println("Does all elements in num2 exist in num1: ${num3.containsAll(num2)}")
//Does all elements in num2 exist in num1: true
println(strList.indexOfFirst { e -> e.startsWith("coo") }) // 1
println(strList.indexOfFirst { e -> e.startsWith("oo") }) //-1
println(strList.indexOfLast { e -> e.endsWith("ook") }) //3
println(strList.find { e -> e.startsWith("to") }) // took
println(strList.find { e -> e.startsWith("oo") }) // null
println(strList.findLast { e -> e.endsWith("ook") }) // look
println(strList.findLast { e -> e.endsWith("oo") }) //null
Kotlin Mutable List
MutableList inherites List and supports read/write access, you can add, update or remove items.
Mutable lists are created using mutableListOf() and mutableListOf()<T>() functions.
Create and initialize mutableList with values
The below example show you how to:
- initialize List using mutableListOf() (contains elements of all type), mutableListOf()<T>() (contains elements of specific type).
- create new List from another List with the same elements using toMutableList() function.
fun main() {
var list1 = mutableListOf("Arun", 10, 1.05f, 'a', null, 10)
var nameList1 = mutableListOf<String>("Arun", "Neha", "Monika")
val nameList2 = nameList1.toMutableList()
println("list1: $list1")
//list1: [Arun, 10, 1.05, a, null, 10]
println("nameList1: $nameList1")
//nameList1: [Arun, Neha, Monika]
println("nameList2: $nameList2")
//nameList2: [Arun, Neha, Monika]
}
Add items to MutableList
The below example shows how to:
- add element to list using add() method.
- insert element into the list at the specified index using add(index, element).
- Add all of the elements of a list to the end of another list using addAll(list).
- Add all of the elements of a list at specified index of another list using addAll(index, list).
val num1 = mutableListOf(0, 1)
num1.add(5)
println(num1) //[0, 1, 5]
num1.add(3, 6)
println(num1) //[0, 1, 5, 6]
num1.addAll(listOf(7,8))
println(num1) //[0, 1, 5, 6, 7, 8]
num1.addAll(2, listOf(4))
println(num1) //[0, 1, 4, 5, 6, 7, 8]
Update/Replace item in MutableList
The examples show you how to:
- update/replace item in mutable List at specified index using set() method or operator[]
- replace all items in mutable List with given value using fill() method.
- replace each item in the list with a result of a function using replaceAll() method.
val nums = mutableListOf(0, 1, "three")
nums.set(1, "one")
println(nums) //[0, one, three]
nums[2] = "two"
println(nums) //[0, one, two]
nums.fill("three")
println(nums) //[three, three, three]
nums.replaceAll({ e -> e.toString().capitalize() + ".com" })
println(nums) //[Three.com, Three.com, Three.com]
Remove items from MutableList
The examples show you how to:
- remove the item at a given index in a List using removeAt(index)
- remove the first occurrence of item from a List by its value using remove(value)
- remove all items from the List that match a given condition or another List using removeAll()
- remove all the items using clear()
val num2 = mutableListOf(0, 1, 2, 3, 4, 3, 5)
//remove items from List
num2.remove(3)
println(num2) //[0, 1, 2, 4, 3, 5]
num2.removeAt(1)
println(num2) //[0, 2, 4, 3, 5]
num2.removeAll(listOf(1, 2, 3))
println(num2) //[0, 4, 5]
num2.removeAll({ it < 3 })
println(num2) //[4, 5]
num2.clear()
println(num2) //[]
Iterate over List in Kotlin
The examples show you how to iterate over a List using:
- simple for loop
- for loop with item index
- forEach() method.
- forEachIndexed() that gives us index and value in each iteration.
- ListIterator and a while loop.
val numbers = listOf<Int>(1, 2, 3)
print("print list using for loop: ")
// print list using for loop
for (number in numbers) {
print("$number, ")
}
println()
// print list using for loop: 1, 2, 3,
print("for loop with item index: ")
for (i in 2 until numbers.size) {
print("${numbers[i]}, ")
}
println()
//for loop with item index: 3,
print("print list using forEach loop: ")
numbers.forEach { i -> print("$i, ") }
println()
//print list using forEach loop: 1, 2, 3,
//forEachIndexed() that gives us index and value in each iteration.
println("print list using forEachIndexed() : ")
numbers.forEachIndexed({ index, i -> println("numbers[$index] = $i") })
println()
//print list using forEachIndexed() :
//numbers[0] = 1
//numbers[1] = 2
//numbers[2] = 3
val i1: ListIterator<Int> = numbers.listIterator()
println("print list using ListIterator in forward direction: ")
while (i1.hasNext()) {
val index = i1.nextIndex()
val element = i1.next()
println("nums[$index] = $element ")
}
println()
//print list using ListIterator in forward direction:
//nums[0] = 1
//nums[1] = 2
//nums[2] = 3
println("print list using ListIterator in backward direction: ")
while (i1.hasPrevious()) {
val index = i1.previousIndex()
val element = i1.previous()
println("nums[$index] = $element ")
}
println()
//print list using ListIterator in backward direction:
//nums[2] = 3
//nums[1] = 2
//nums[0] = 1
// using ListIterator
// print list in forward direction
// starting at the specified index
print("print list using ListIterator starting at the specified index: ")
val it: ListIterator<Int> = numbers.listIterator(2)
while (it.hasNext()) {
val element = it.next()
print("$element, ")
}
println()
//print list using ListIterator starting at the specified index: 3,
}