Site icon C1CTech

Kotlin List

In this tutorial, we will talk about Kotlin List with the help of simple examples.

List 

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

   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,
}

Exit mobile version