kotlin-list-mutable-list-complete-reference-feature-image

Kotlin List & Mutable List tutorial with examples (Part 1)

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


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 inherites List 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:

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:

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:

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.
  • get the first or last items of a List using take() or takeLast() method.
  • get the first items of a List satisfying the given condition using takeWhile() method.
  • get 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.subList(2, 5)              // [2, 3, 4]

nums.slice(2..5)                // [2, 3, 4, 5]

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]
  • get subList that contains all items except first items or last items using drop() or dropLast()
  • get subList containing all items except first items that satisfy a given condition using dropWhile()
  • get subList containing all items except 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:

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 items in List

The examples show how to:

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

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 tutorial, I will show you more:

  • How to filter, transform, group items in Kotlin list
  • How to create List of objects in Kotlin
  • Ways to sort a Mutable List (of objects) in Kotlin

Happy learning! See you again!

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *