Section 1.9 Collections
Kotlin provides a number of collections, some of which implement the data structures we will be looking at in this book. (Later on in this book, we will be implementing our own versions of these data structures rather than relying on the ones that Kotlin gives us.)
Subsection 1.9.1 The MutableList
The primary collection weβll be using is the
MutableList. Kotlin distinguishes between the collection List, which is immutable (or unchangeable) after it has been created, and the collection MutableList, which enables you to make changes to it. Most of the time we are doing interesting coding, we want a MutableList. The immutable List is mostly useful if you want a short fixed list for a singular purpose.
Letβs create a
MutableList of String elements. The element data type is enclosed in angle brackets, and is a generic. All the elements in a MutableList must be of the same data type.
fun main() {
val animals = mutableListOf<String>()
println(animals) // []
animals.add("ibex")
animals.add("capybara")
animals.add("bison")
println(animals) // [ibex, capybara, bison]
animals.add(1, "giraffe")
println(animals) // [ibex, giraffe, capybara, bison]
}
The
add method appends items to the end of the list and returns true. A two-argument version of add lets you give an index position at which to add an element, but it does not return any value. The first element in an MutableList has index zero.
Here are examples of other commonly-used
MutableList operations, demonstrated on the list animals:
Method
|
Purpose
|
|---|---|
animals.count()
|
Returns number of elements in list
|
animals[index]
|
Returns the element at the given index in the list
|
animals[index] = element
|
Replaces item at given index with the given element.
|
animals.removeAt(index)
|
Removes and returns the element at the given index
|
animals.indexOf(element)
|
Returns index of the first occurrence of the element in the list, or -1 if element is not in list.
|
Subsection 1.9.2 The MutableMap
Another important collection type in Kotlin is an unordered structure called a map. A map, also known as a dictionary, is a collection of associated pairs of items where each pair consists of a key and a value. Unlike lists which are indexed by number, you access values in a map by their keys. Kotlin contains a
Map collection, which is immutable, and a MutableMap, which can be modified after it has been created. As with lists, MutableMap is generally the more useful of the two. For example, if we want to represent TableΒ 1.9.2 of cities and their populations (according to 2018 estimates by the United Nations):
| City | Population |
|---|---|
| New York City | 7,888,121 |
| Tokyo | 13,515,271 |
| Dhaka | 8,906,039 |
| Luanda | 2,165,867 |
We would use this code:
fun main() {
val cityInfo = mutableMapOf<String, Int>()
cityInfo["New York City"] = 7_888_121
cityInfo["Tokyo"] = 13_515_271
cityInfo["Dhaka"] = 8_906_039
cityInfo["Luanda"] = 2_165_867
println(cityInfo)
println()
for (key in cityInfo.keys) {
println(String.format(
"Key %s has value %,d.",
key, cityInfo[key]
))
}
}
Line 2 creates the map, where we put the data types for the key and value inside angle brackets.
Lines 3-6 add keys and values to the map. If a key already is in the HashMap, the value given as the second argument will replace the current map value.
Aside
Hereβs the output from line 8:
{New York City=7888121, Tokyo=13515271, Dhaka=8906039, Luanda=2165867}
It is important to note that Kotlin has alternative map implementations (other than the default mutable map that Kotlin automatically provides) that donβt necessarily display the keys in the same order that you put them in. The placement of a key is dependent on the idea of hashing, which will be explained in more detail in Chapter 5. The default mutable map implementation in Kotlin (known as a
LinkedHashMap) does maintain the order, so in the example above the pairs appear in the order they were added.
You can, then, iterate through a map as shown in lines 11-15 above. That produces this output:
Key New York City has value 7,888,121. Key Tokyo has value 13,515,271. Key Dhaka has value 8,906,039. Key Luanda has value 2,165,867.
(You will learn more about the
String.format method later.
| Method | Purpose |
|---|---|
cityInfo.count()
|
Returns number of key/value pairs in the map
|
cityInfo[key]
|
Returns the value associated with the given key
|
cityInfo[key] = value
|
Replaces value for given key if it is in the map already; adds a new key and value if not. Returns the value previously associated with the key, or null if not previously in map.
|
cityInfo.remove(key)
|
Removes the specified key and its value. Returns the value for the given key, or null if key is not in the map.
|
cityInfo.keys
|
Returns a collection of the keys contained in the map.
|
key in cityInfo
|
Subsection 1.9.3 The MutableSet
A set is an unordered collection of zero or more objects. Sets do not allow duplicates. As with the other collections, Kotlin contains both an immutable
Set and a MutableSet.
Here are the commonly-used
MutableSet methods:
Method
|
Purpose
|
|---|---|
add(element)
|
If the element is not in the set, adds the element and returns true; otherwise, returns false and leaves the set unchanged
|
remove(element)
|
If the element is in the set, removes the object from the set and returns true; otherwise returns false and leaves the set unchanged
|
contains(element)
|
You have attempted of activities on this page.

