Kotlin provides many useful functions that can come in handy when you work with lists and modify their contents. In this topic, we'll look at various groups of commonly used functions and show you how to use them with examples.
Outputting a list
The first function is joinToString(). It helps us output our list in different ways using the separator attribute.
Use joinToString() to see the resulting list and print its contents:
val southernCross = mutableListOf("Acrux", "Gacrux", "Imai", "Mimosa")
println(southernCross.joinToString()) // Acrux, Gacrux, Imai, Mimosa
Remember that joinToString() takes elements from a mutable list in the order in which they are stored and presents them as a comma-delimited string line.
You can also use another delimiter to separate elements :
println(southernCross.joinToString(" -> ")) // Acrux -> Gacrux -> Imai -> MimosaWorking with multiple lists
Now, let’s look at a couple of things you might want to know about when working with several string lists.
Mutable lists can be joined.
You can concatenate several lists as shown in the following example:
val southernCross = mutableListOf("Acrux", "Gacrux", "Imai", "Mimosa")
val stars = mutableListOf("Ginan", "Mu Crucis")
val newList = southernCross + stars
println(newList.joinToString()) // Acrux, Gacrux, Imai, Mimosa, Ginan, Mu Crucis
Mutable lists can be compared.
You can use the operators == and != to compare lists – their contents and sizes:
val firstList = mutableListOf("result", "is", "true")
val secondList = mutableListOf("result", "is", "true")
val thirdList = mutableListOf("result")
println(firstList == secondList) // true
println(firstList == thirdList) // false
println(secondList != thirdList) // true
Note that true is returned only if the elements of the two lists match completely and are arranged in the same order.
Changing the list contents
The keywords val and var tell you how the value/reference of a variable should be handled.
var – the value/reference assigned to a variable can be changed at any time.
val – the value/reference can be assigned to a variable only once and cannot be changed later during the execution.
No matter which keyword you're using, val or var, you can still edit the values of the existing elements through their index. This is possible because when we change the contents of a list, we do not create a new list (the link to the list is not changed):
val southernCross = mutableListOf("Acrux", "Gacrux", "Imai", "Mimosa")
var stars = mutableListOf("Ginan", "Mu Crucis")
southernCross[1] = "star"
stars[1] = "star"
println(southernCross[1]) // star
println(stars[1]) // star
There are ways to remove list elements and add new elements to the list.
You can use the functions add, remove, and clear to change lists:
val southernCross = mutableListOf("Acrux", "Gacrux", "Imai", "Mimosa")
val stars = mutableListOf("Ginan", "Mu Crucis")
val names = mutableListOf("Jack", "John", "Katie")
val food = mutableListOf("Bread", "Cheese", "Meat")
val fruits = mutableListOf("Apple", "Banana", "Grape", "Mango")
southernCross.removeAt(0)
southernCross.remove("Mimosa")
stars.add("New star")
stars.add(0, "First star")
names.clear()
food.addAll(fruits)
println(names) // []
println(southernCross.joinToString()) // Gacrux, Imai
println(stars.joinToString()) // First star, Ginan, Mu Crucis, New star
println(food.joinToString()) // Bread, Cheese, Meat, Apple, Banana, Grape, Mango
add(element)andadd(index, element)insert new items at any position in the list. If you don't specify the index, the item will be added to the end of the list.list1.addAll(list2)adds all elements fromlist2to the end of thelist1.remove(element)andremoveAt(index)delete an item from the list. The former function deletes a single instance of the specified element from the list (it returnstrueif the item was successfully removed, otherwise it returnsfalse). The latter function deletes the element at the specified position and returns the element that has been removed.clear()deletes all elements from the list.
Also, you can use += to add new elements to the list:
val vowels = mutableListOf('a', 'o', 'i', 'e', 'u')
val intList1 = mutableListOf(1, 2, 3, 4, 5)
val intList2 = mutableListOf(5, 4, 3, 2, 1)
vowels += 'y'
intList1 += intList2
println(vowels) // [a, o, i, e, u, y]
println(intList1) // [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]Copy list content
Kotlin doesn't have any functions to copy existing lists. However, you can do it using the toMutableList() function:
val list = mutableListOf(1, 2, 3, 4, 5)
val copyList = list.toMutableList()
print(copyList) // [1, 2, 3, 4, 5]
This function creates a new MutableList and adds the contents of list to the new list. It works like this:
val list = mutableListOf(1, 2, 3, 4, 5)
val copyList = mutableListOf<Int>()
copyList.addAll(list)
print(copyList) // [1, 2, 3, 4, 5]Other useful functions
There are some operations that can be really useful when you work with lists and their contents:
list.isEmpty()andlist.isNotEmpty()– check whether the list is empty.list.subList(from, to)– creates a smaller list (sublist), which includes items of the original list with the following indexes:from,from + 1, ...,to - 2,to - 1. The element with the indextois not included.
val numbers = mutableListOf(1, 2, 3, 4, 5)
var sublist = mutableListOf<Int>()
if (numbers.isNotEmpty() && numbers.size >= 4) {
sublist = numbers.subList(1, 4)
}
print(sublist) // [2, 3, 4]
list.indexOf(element)– searches for the index of an element in the list. The result of this function is -1 if there is no such element in the list. Otherwise, when we access the list by the calculated index, we get the element.
val numbers = mutableListOf(1, 2, 3, 4, 5)
if (5 in numbers) {
println(numbers.indexOf(5)) // 4
}
print(numbers.indexOf(7)) // -1
list.minOrNull()andlist.maxOrNull()– search for the minimum and maximum elements in the list.list.sum()– returns the sum of the elements in the list.list.sorted()andlist.sortedDescending()– build a sorted list (ascending or descending) from the available list.
val numbers = mutableListOf(1, 2, 3, 4, 5)
val vowels = mutableListOf('e', 'a', 'y', 'i', 'u', 'o')
println(numbers.minOrNull()) // 1
println(numbers.maxOrNull()) // 5
println(numbers.sum()) // 15
println(vowels.sorted()) // [a, e, i, o, u, y]
println(vowels.sortedDescending()) // [y, u, o, i, e, a]Conclusion
Let's sum things up now! You've figured out how to use some familiar functions and techniques when working with mutable lists.
Now you can:
use
joinToString()to create a single string from the list and output it;use
==and!=to compare two mutable lists;add new elements to a list or remove elements from it;
perform various manipulations on lists and list elements.
This is a lot of material! Good news for you: you can work with mutable lists of any type in the same way. Good luck!