In this tutorial, I will show you many methods and functions to work with List & MutableList in Kotlin. You’re gonna know:
- Introduction to Kotlin List
- How to create, initialize, access, update, remove items in a MutableList
- How to combine multiple Lists, get subList of a List in Kotlin
- Ways to iterate, reverse, find items in a Kotlin List
Related Posts:
– Kotlin – Sort List of custom Objects
– Kotlin Queue tutorial with examples
– Kotlin HashMap tutorial with examples
Contents
- Important points about Kotlin List & MutableList
- Create List, MutableList in Kotlin
- Kotlin Initialize List, MutableList with values
- Add items to List in Kotlin
- Add list to mutable list in Kotlin
- Kotlin combine multiple lists
- Access items from List in Kotlin
- Get subList of a List in Kotlin
- Kotlin List take
- Kotlin List drop
- Kotlin Update/Replace item in List
- Kotlin remove items from List
- Iterate over List in Kotlin
- Reverse List in Kotlin
- Kotlin find object in List
- Sort List in Kotlin
- Conclusion
- Further Reading
Important points about Kotlin List & MutableList
These are some important points you should know before working with Kotlin MutableList:
List
is read-only (immutable), you cannot add or update items in the original list.MutableList
inheritesList
and supports read/write access, you can add, update or remove items.List
&MutableList
are ordered collections in which the insertion order of the items is maintained.List
&MutableList
allows duplicates and null values
Create List, MutableList in Kotlin
We create a new empty List, MutableList using mutableListOf() method. We can specify the type of items in the List (Int
, String
…). For different data types, or for object types, we’re gonna use Any
.
package com.bezkoder.kotlin.mutablelist
fun main(args: Array) {
val intList: List = listOf()
val stringList: List = listOf()
val anyList: List = listOf()
val intMutableList: MutableList = mutableListOf()
val stringMutableList: MutableList = mutableListOf()
val anyMutableList: MutableList = mutableListOf()
}
Kotlin Initialize List, MutableList with values
The examples show you how to:
- initialize
List
using listOf() and listOfNotNull() functions. - initialize
MutableList
using mutableListOf(). - create new
List
,MutableList
using Initializer functions. - create new
List
,MutableList
from anotherList
,MutableList
with the same elements using toList(), toMutableList() functions.
val stringList = listOf("bezkoder.com", "programming", "tutorial")
// [bezkoder.com, programming, tutorial]
val anyList1 = listOf("bezkoder.com", 2019)
// [bezkoder.com, 2019]
val anyList2 = listOf("bezkoder.com", 2019, null)
// [bezkoder.com, 2019, null]
val anyList3 = listOfNotNull("bezkoder.com", 2019, null)
// [bezkoder.com, 2019]
val intMutableList = mutableListOf(1, 2, 3)
// [1, 2, 3]
val anyMutableList1 = mutableListOf("bezkoder.com", 2019, "kotlin")
// [bezkoder.com, 2019, kotlin]
val anyMutableList2 = mutableListOf("bezkoder.com", 2019, "kotlin", null)
// [bezkoder.com, 2019, kotlin, null]
// val intList1 = List(3, { i -> i * 2 })
val intList1 = List(3) { i -> i * 2 }
// [0, 2, 4]
// val intList2 = MutableList(3, { i -> (i + 1) * 2 })
val intList2 = MutableList(3) { i -> (i + 1) * 2 }
// [2, 4, 6]
val intList1 = listOf(1, 2, 3)
val intList2 = intList1.toList()
// [1, 2, 3]
val intMutableList2 = intList1.toMutableList()
// [1, 2, 3]
val stringList1 = mutableListOf("bezkoder", "kotlin", "android")
val stringList2 = stringList1.toList()
// [bezkoder, kotlin, android]
val stringMutableList2 = stringList1.toMutableList()
// [bezkoder, kotlin, android]
Add items to List in Kotlin
List
doesn’t accept us to add items. So we can only do this with MutableList
.
The examples show ways to:
- add item to list using add() method.
- insert item into the list at the specified index.
- add item to list using plus (+) operator.
val anyMutableList = mutableListOf()
anyMutableList.add("bezkoder.com");
anyMutableList.add("tutorials");
// [bezkoder.com, tutorials]
anyMutableList.add(1, 2019)
// [bezkoder.com, 2019, tutorials]
anyMutableList += "kotlin"
// [bezkoder.com, 2019, tutorials, kotlin]
Add list to mutable list in Kotlin
In the following code, we will add list to mutable list:
- using addAll() method
- at specified index.
- using plus (+) operator.
val list = mutableListOf(1, 2)
val list1 = listOf(5, 6)
list.addAll(list1)
// [1, 2, 5, 6]
list.addAll(2, listOf(3, 4))
// [1, 2, 3, 4, 5, 6]
list += listOf(7, 8)
// [1, 2, 3, 4, 5, 6, 7, 8]
Kotlin combine multiple lists
The examples show you how to combine multiple lists to a Kotlin MutableList
using:
- plus() method
- plus (+) operator
- addAll() method
listOf()
function, toTypedArray() with spread operator
val list1 = listOf(1, 2)
val list2 = listOf(3, 4)
val list3 = listOf(5, 6)
val combinedlist1 = list1.plus(list2).plus(list3)
val combinedlist2 = list1 + list2 + list3
val combinedlist3 = list1.toMutableList()
combinedlist3.addAll(list2)
combinedlist3.addAll(list3)
val combinedlist4 = listOf(*list1.toTypedArray(), *list2.toTypedArray(), *list3.toTypedArray())
// [1, 2, 3, 4, 5, 6]
Access items from List in Kotlin
The examples show you how to:
- find the size of a List using
.size
getter or count() method. - 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 nums = listOf(1, 2, 3, 4, 5)
nums.count() // 5
nums.size // 5
nums.isEmpty() // false
nums.isNotEmpty() // true
nums[2] // 3
nums.get(2) // 3
nums.getOrElse(6, { -1 }) // -1
nums.getOrNull(6) // null
Get subList of a List in Kotlin
In the examples, we’re gonna:
- 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 nums = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8)
nums.subList(2, 5) // [2, 3, 4]
nums.slice(2..5) // [2, 3, 4, 5]
Kotlin List take
- take the first or last items of a List using take() or takeLast() method.
- take the first items of a List satisfying the given condition using takeWhile() method.
- take sublist that contains the last items of a List satisfying the given condition using takeLastWhile() method.
val nums = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8)
nums.take(3) // [0, 1, 2]
nums.takeWhile { it < 5 } // [0, 1, 2, 3, 4]
nums.takeLast(3) // [6, 7, 8]
nums.takeLastWhile { it > 6 } // [7, 8]
Kotlin List drop
- 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 nums = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
nums.drop(3) // [3, 4, 5, 6, 7, 8]
nums.dropWhile { it < 5 } // [5, 6, 7, 8]
nums.dropLast(3) // [0, 1, 2, 3, 4, 5]
nums.dropLastWhile { it > 3 } // [0, 1, 2, 3]
Kotlin Update/Replace item in List
Update or replace operations only work with Kotlin mutable List.
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 list = mutableListOf(0, 1, 2, 3)
list.set(3, "three")
// [0, 1, 2, three]
list[0] = "zero"
// [zero, 1, 2, three]
list.fill("bezkoder")
// [bezkoder, bezkoder, bezkoder, bezkoder]
list.replaceAll { e -> e.toString().capitalize() + ".com" }
// [Bezkoder.com, Bezkoder.com, Bezkoder.com, Bezkoder.com]
Kotlin remove items from List
The examples show you how to:
- remove the item at a given index in a List | removeAt(index)
- remove first element from List or last element from List in Kotlin |
removeAt()
- remove the first occurrence of item from a List by its value | remove(value)
- remove all items from the List that match a given condition or another List | removeAll()
- remove all the items | clear()
- remove all items from the List that are in another List using minus (-) operator
val nums = mutableListOf(-3, -2, 4, -1, 0, 1, 2, 3, 4, 2, 5, 6, 5, 8)
nums.removeAt(4)
// [-3, -2, 4, -1, 1, 2, 3, 4, 2, 5, 6, 5, 8]
nums.remove(4)
// [-3, -2, -1, 1, 2, 3, 4, 2, 5, 6, 5, 8]
nums.removeAll(listOf(1, 2, 3))
// [-3, -2, -1, 4, 5, 6, 5, 8]
nums.removeAll({ it < -1 })
// [-1, 4, 5, 6, 5, 8]
nums -= listOf(4, 5)
// [-1, 6, 8]
nums.removeAt(0) // remove first element
// [6, 8]
nums.removeAt(nums.size - 1) // remove last element
// [6]
nums.clear()
// []
Iterate over List in Kotlin
The examples show you how to iterate over a Dart List using:
- forEach() method.
- simple for loop
- ListIterator and a while loop.
- for loop with item index
- forEachIndexed() that gives us index and value in each iteration.
val numbers = listOf(0, 1, 2, 3, 4, 5)
numbers.forEach { i -> print(">$i ") }
// >0 >1 >2 >3 >4 >5
for (number in numbers) {
print(">$number ")
}
// >0 >1 >2 >3 >4 >5
val listIterator = numbers.listIterator()
while (listIterator.hasNext()) {
val i = listIterator.next()
print(">$i ")
}
// >0 >1 >2 >3 >4 >5
for (i in 0 until numbers.size) {
print(">${numbers[i]} ")
}
// >0 >1 >2 >3 >4 >5
numbers.forEachIndexed({ idx, i -> println("numbers[$idx] = $i") })
/*
numbers[0] = 0
numbers[1] = 1
numbers[2] = 2
numbers[3] = 3
numbers[4] = 4
numbers[5] = 5
*/
Reverse List in Kotlin
The examples show you how to:
- get a new List with revered order using reversed() method.
- get a reversed read-only list of the original List as a reference using asReversed() method. If we update item in original list, the reversed list will be changed too.
val numbers = mutableListOf(0, 1, 2, 3)
val reversedNumbers = numbers.reversed()
// reversedNumbers: [3, 2, 1, 0]
numbers[3] = 5
// numbers: [0, 1, 2, 5]
// reversedNumbers: [3, 2, 1, 0]
val numbers = mutableListOf(0, 1, 2, 3)
val refReversedNumbers = numbers.asReversed()
// refReversedNumbers: [3, 2, 1, 0]
numbers[1] = 8
// numbers: [0, 8, 2, 3]
// refReversedNumbers: [3, 2, 8, 0]
Kotlin find object in List
The examples show how to:
- check if a List contains an object or not | contains() or
in
- check if a List contains all given objects or not | containsAll()
- find the index of the first/last occurrence of an object | indexOf() / lastIndexOf()
- find the index of the first/last occurrence of an object that matches a condition | indexOfFirst() / indexOfLast()
- find the first/last item in the list that matches a condition | find() / findLast()
val list =
listOf("bezkoder", 2019, "kotlin", "tutorial", "bezkoder.com", 2019)
list.contains("bezkoder") // true
list.contains("zkoder") // false
"bezkoder" in list // true
list.containsAll(listOf("bezkoder", "tutorial")) // true
list.containsAll(listOf("zkoder", "tutorial")) // false
list.indexOf(2019) // 1
list.lastIndexOf(2019) // 5
list.indexOf(2020) // -1
list.lastIndexOf(2020) // -1
list.indexOfFirst { e -> e.toString().startsWith("bez") } // 0
list.indexOfFirst { e -> e.toString().startsWith("zkoder") } // -1
list.indexOfLast { e -> e.toString().endsWith("9") } // 5
list.indexOfLast { e -> e.toString().endsWith(".net") } // -1
list.find { e -> e.toString().startsWith("bez") } // bezkoder
list.find { e -> e.toString().startsWith("zkoder") } // null
list.findLast { e -> e.toString().endsWith("9") } // 2019
list.findLast { e -> e.toString().endsWith(".net") } // null
Sort List in Kotlin
It's more complicated, so I write in a separated Tutorial. You can find at:
How to sort List in Kotlin
Conclusion
In this tutorial, we've learned overview of a Kotlin List & Mutable List, how to create a List, how to add, update and remove items from a List, how to iterate over a List, how to combine Lists, get subList, reverse a List, find items/ index of items in a List.
In the next tutorials, I will show you more:
- How to filter, transform, group items in Kotlin list
- How to create & sort List of objects in Kotlin
Kotlin groupBy, groupByTo, groupingBy example
Happy learning! See you again!
Just want to say thanks for the tutorial.
Thanks in advance!
Good explained, unfortunately I’m still stuck with “How to modify items in Kotlin collections using functional approaches like a std::transform”
Full of knowledge and practice for Kotlin List. Thanks!
Clean and comprehensive Kotlin List tutorial!
Thanks a lot!