Kotlin Programming – Collection Types

In this tutorial you’ll learn about collection types in Kotlin. To follow along, you can make use of the Kotlin – Playground.

Collection Types

There are three primary collection types in Kotlin for storing of collections values:

  • Lists
  • Sets
  • Maps

Lists

You use a list when you want to store an ordered collections of values.

Creating an Empty List

You can create an empty list of a certain type and then add values to it.

val numbers = mutableListOf<Int>() // empty list
numbers.add(15) // list has 1 value where numbers now become [15]

Note that you are not required to declare your list with var in order to be able to add elements to it. However, using val while declaring a list, will not allow you to set the list to another.

Creating a List with Values

You can create a list with some values and Kotlin will infer the type automatically.

val groceryList = mutableListOf("Fruits", "Yogurt", "Vegetables")

Accessing and Modifying a List

If you have to find out if a list contains some values, you can either use the ‘size’ property or the Boolean ‘isEmpty()’ method.

println("groceryList contain ${groceryList.size} items") // groceryList.size returns 3
 
if (groceryList.isEmpty()) {
    println("No need to go to the supermarket")
} else { // groceries is not empty therefore groceryList.isEmpty() returns false
    println("Need to buy groceries")
}

You can use the ‘add()’ method to add new items to the groceryList.

groceryList.add("Bread")

You can get the first item in the groceryList by using subscript syntax, which means passing the index of the item you want to retrieve. Index starts with 0 in Kotlin, which means that to get the first item of the groceryList, you should pass the index 0.

var firstItem = groceryList[0]

You can use the subscript syntax to change an existing value at a given index.

groceryList[0] = "Apple"
firstItem = groceryList[0]

You can remove an item at a specific index using the removeAt() method.

groceryList.removeAt(0)

Iterating Over a List

You can iterate over the groceryList’s items using the for-in loop.

for (item in groceryList) {
    println("item is $item")
}

Sets

You use a set when you want to store an unordered collections of unique values.

Creating and Initializing an Empty Set

You can create an empty set of a certain type and then insert values in it.

val alphabets = mutableSetOf<Char>() // empty set
alphabets.add('a') // set has 1 value where alphabets now become [a]

Creating a Set with Values

You can create a set with some values and Kotlin will infer the type automatically.

val favoriteTvShows = mutableSetOf("Charmed", "Prison Break", "Money Heist")

Accessing and Modifying a Set

If you have to find out if a set contains some values, you can either use the ‘size’ property or the Boolean ‘isEmpty()’ method.

println("favoriteTvShows contain ${favoriteTvShows.size} items") // favoriteTvShows.size returns 3
 
if (favoriteTvShows.isEmpty()) {
    println("I like most of the popular tv shows")
} else { // favoriteTvShows is not empty therefore favoriteTvShows.isEmpty() returns false
    println("I have some favorite tv shows")
}

You can add a new item using the add() method.

favoriteTvShows.add("The Flash")

You can remove an item using the remove() method.

favoriteTvShows.remove("Charmed")
println("I have watched Charmed too many times")

You can check if an item exists in a set.

if (favoriteTvShows.contains("Prison Break")) {
    println("I have reached Season 3")
} else {
    println("I have watched all the seasons of my favorite tv shows")
}

Iterating Over a Set

You can iterate over the favoriteTvShow’s items using the for-in loop.

for (favoriteTvShow in favoriteTvShows) {
    println(favoriteTvShow)
}

You can iterate over the favoriteTvShow’s items in a sorted way.

for (favoriteTvShow in favoriteTvShows.sorted()) {
    println(favoriteTvShow)
}

Maps

You use a map when you want to store an unordered collections of key-value associations.

Creating an Empty Map

You can create an empty map of a certain type and then add key-value to it.

val records = mutableMapOf<Int, String>() // empty map
records.put(1, "Kotlin") // map has 1 key-value where records now become {1=Kotlin}
// or
records[2] = "Android" // {1=Kotlin, 2=Android}

Creating a Map with Values

You can create a map with some values and Kotlin will infer the type automatically.

val countries = mutableMapOf("US" to "United States of America", "UK" to "United Kingdom", "FR" to "France", "MU" to "Mauritius")

Accessing and Modifying a Map

If you have to find out if a map contains some values, you can either use the ‘size’ property or the Boolean ‘isEmpty()’ method.

println("countries contain ${countries.size} items") // countries.size returns 4
 
if (countries.isEmpty()) {
    println("No countries found")
} else { // countries is not empty therefore countries.isEmpty() returns false
    println("Some countries found")
}

You can add a new item using the subscript syntax.

countries["AU"] = "Australia"
countries["CA"] = "CA"
countries["GR"] = "GR"

You can update a value using the subscript syntax.

countries["CA"] = "Canada"
countries["GR"] = "Greece"

You can retrieve a value using the subscript syntax.

var retrievedValue = countries["MU"]

if (retrievedValue != null) {
    println("$retrievedValue's country code is MU")
} else {
    println("No such key was found")
}

You can remove a value using the remove() method.

countries.remove(key: "AU")
println("AU has been removed from $countries")

Iterating Over a Map

You can iterate over the countries’ items using the for-in loop.

for ((countryCode, country) in countries) {
    println("Code $countryCode is for $country")
}

Alternatively you can iterate over the countries’ items using the forEach loop.

countries.forEach { countryCode, country ->
    println("Code $countryCode is for $country")
}

Reference

https://kotlinlang.org/docs/reference/collections-overview.html