Learn the Basics of the Kotlin Language

May 22 2024 · Kotlin 1.9, Android 14, Kotlin Playground 1.9

Lesson 06: Use Collections

Demo 2

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll learn more about Kotlin Collections with Sets and Maps. Start a new Kotlin Playground session to follow along with the demo. Or you could use any other Kotlin programming environment of your choice.

Set

A set stores only unique values. If add() is called on a Set and the added item is a duplicate within the Set, it won’t be added. For this reason, the order of a Set isn’t defined, as some items may be removed if duplicated. Sets in Kotlin are represented by the Set interface.

Read-only Sets

A set may also be mutable or immutable, just like a List. To initialize an immutable set, use setOf:

fun main() {
  val oceans = setOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans)
}

When you run the program, the items may appear to be in order. But keep in mind that this isn’t always the case.

Mutable Sets

Use mutableSetOf to initialize a mutable Set:

fun main() {
  val oceans = mutableSetOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
}

To add items to a mutable set, call the add method on the object to add a single item or addAll to add all items from another collection:

fun main() {
  val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
  oceans.add("Pacific Ocean")
  oceans.addAll(listOf("Southern Ocean", "Arctic Ocean"))
  println(oceans)
}

In the output console, take a look at the printed results. Oceans has been updated successfully.

Remember that a set doesn’t accept duplicates? Add Pacific Ocean again, and check the output:

fun main() {
  val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
  oceans.add("Pacific Ocean")
  oceans.addAll(listOf("Southern Ocean", "Arctic Ocean"))
  oceans.add("Pacific Ocean")
  println(oceans)
}

The output remains the same.

To reference an element by its index, use elementAt:

fun main() {
  val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
  println(oceans.elementAt(0))
}

As expected, the first element is printed to the console.

And to remove an element, use remove(), passing the item to remove as an argument:

fun main() {
  val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
  oceans.remove("Atlantic Ocean")
  println(oceans)
}

After executing the program, you can see that Atlantic Ocean is removed from the set.

Use emptySet to create an empty Set:

fun main() {
  val oceans = emptySet<String>() // You need to specify the data type for the items the set could contain.
}

Sets can be iterated just like lists.

fun main() {
  val digits = setOf(1,2,3,4,5)
    for (digit in digits){
        println(digit)
    }
}

Map

A Map differs from the List and Set in that they store key-value pairs instead of single items. A key in a Map is unique. If a new key duplicates an existing key, the existing key’s value is updated with the new one.

A map can be empty. To initialize an empty map, use the emptyMap built-in function. You need to specify the type for both the key and value. This is the same initialization you wrote for List and Set:

fun main() {
  emptyMap<Int, String>()
}

A map may be immutable by assigning the Map to a val. To assign a value to a key, separate the key from the value using the keyword to. Create a map of some popular tech blogs on the web:

fun main() {
  val techBlogs = mapOf(1 to "TechCrunch", 2 to "Engadget", 3 to "The Verge", 4 to "Mashable")
  println(techBlogs)
}

Take note of the structure of a map from the output console below.

A Map may be mutable. Use mutableMapOf to create a mutable map. And use the put function to add “VentureBeat” to the map with the key being 5:

fun main() {
  val techBlogs = mutableMapOf(1 to "TechCrunch", 2 to "Engadget", 3 to "The Verge", 4 to "Mashable")
  println(techBlogs)
  techBlogs.put(5, "VentureBeat")
  println(techBlogs)
}

Maps created with mapOf are immutable. They don’t have any such functions like the put() function for updating the map.

When iterating over a map, use the iterator() function of the entries property to access the key-value pairs:

fun main() {
  val techBlogs = mapOf(1 to "TechCrunch", 2 to "Engadget", 3 to "The Verge", 4 to "Mashable")
  for (blog in techBlogs.entries.iterator()) {
      println("${blog.key} : ${blog.value}")
  }
}

You can also iterate over the keys only using the keys property or the values only using the values property.

Arrays

In Kotlin, arrays are used to store a group of items, like other collections you may have encountered before. The Array class represents an array, which differs primarily in its properties. Arrays can store a series of items that are of the same data type or subtype and can’t be changed once created, making them immutable.

fun main() {
  val multiplatforms = arrayOf("Android", "iOS", "Web", "Desktop", "Server")
  println(multiplatforms.toList())
}

To see the items in the Array, you can convert it to a List usint toList().

To create an empty array, your guess is as good as mine. Use emptyArray:

fun main() {
  emptyArray<String>()
}

It is possible to create an Array using its constructor. When doing so, you’ll need to specify the size of the array as well as the initial data that should be pre-populated in it. This will create an array with the specified size and pre-populated data:

fun main() {
  val books = Array<Int>(3) { 0 }
  println(books.toList())
}

Run the code. The books array has three items, with all of them being zero.

The constructor’s initialization code has an implicit variable ‘it’, which holds the index of the array’s items. Use this knowledge to recreate the ‘books’ array with a factor of 2.

fun main() {
  val books = Array<Int>(3) { it * 2 }
  println(books.toList())
}

Run the code. This time, each of the items has been multiplied in place by a factor of 2.

Arrays are a useful way to store a group of items that won’t change throughout your program. They offer many optimizations that make them practical for this purpose. However, arrays don’t have as many convenience methods as lists do.

Like lists, you can access items in an array based on their index, starting from position zero for the first item. Use arrayOf to create an array of the multiple platforms Kotlin supports:

fun main() {
  val multiplatforms = arrayOf("Android", "iOS", "Web", "Desktop", "Server")
  println(multiplatforms[2])
}

This program prints “Web” to the console.

To update an item, specify it by its position and assign the new value. Remove Android from the array, and add it at the first index:

fun main() {
  val multiplatforms = arrayOf("iOS", "Web", "Desktop", "Server")
  multiplatforms[0] = "Android"
  println(multiplatforms.toList())
}

With this, iOS is replaced with Android.

Comparing Arrays

To compare arrays, use contentEquals(). The items will have to be the same in both arrays and at the same position for the two arrays to be equal:

fun main() {
  val multiplatformsA = arrayOf("iOS", "Web", "Desktop", "Server")
  val multiplatformsB = arrayOf("iOS", "Web", "Desktop", "Server")
  println(multiplatformsA.contentEquals(multiplatformsB))
}

It prints true since all the conditions for equality have been met.

Collection Elements

The items in a collection are typically of the same type, but they can also be of different types or subtypes. Create a list made up of a string, a float, a boolean, and a map:

fun main() {
  val mixedTypesList = listOf("Doughnuts", 200.0f, true, mapOf("color" to "Red"))
  println(mixedTypesList)
}

That’s all for this demo. Continue to the concluding segment of using collections in Kotlin.

See forum comments
Cinema mode Download course materials from Github
Previous: Demo 1 Next: Conclusion