Kotlin Collections: Getting Started

In this tutorial, you’ll learn how to work with Kotlin Collections. You’ll transform data, filter it out, and use different types of collections in Kotlin! By Filip Babić.

Leave a rating/review
Download materials
Save for later
Share

Most people think programming is hard and involves dealing with a lot of complex mechanisms. But, when you think about it, most of what programmers do every day is work with data.

Much like the Sith, data rarely comes alone! This is why it’s crucial to work with groups, or collections, of data in our everyday lives.

In this tutorial, you’ll learn how to do that with Kotlin collections. Throughout the tutorial, you’ll:

  • See which Kotlin collection types exist.
  • Compare Kotlin collections types and what you should use them for.
  • Learn how to use different types of Kotlin collections.
  • Explore Kotlin collections operators.
  • Transform data in collections, using various operators.
  • Group and filter data according to different conditions.
Note: If you’re new to Kotlin, it’s highly recommended that you start with Beginning Android Development with Kotlin. This tutorial will focus only on Kotlin, but you can apply everything you learn to Android development.

Getting Started

Download the starter project using the Download materials button at the top or bottom of the tutorial. Open Android Studio 3.4.2 or later and choose Open an existing Android Studio project. Then select the project you just extracted.

Note: To avoid downloading and installing IntelliJ or Android Studio, you can use the Kotlin Playground tool for playing around with the language. All the code can be executed in the playground.

If you open the starter project, you’ll see a lot of small, empty files, separated in their respective packages. Moreover, each file will represent one section of the tutorial and Kotlin collections.

Project structure

Project structure

You’ll only use one file at a time to learn about collections. So by the end, you should cover every topic within a separate file. However, if you’ve chosen to follow the tutorial in the Kotlin Playground, you should see something like the following image when you open the website:

Kotlin Playground

Kotlin Playground

On the left-hand side, you have the code editor, in which you’ll add all the snippets of code. And on the right-hand side, you have buttons to run the code, change the version of Kotlin and share the code.

But that’s enough talk about the projects, time to start learning!

What are Collections?

If you’ve got some experience with programming, you should know there’s a small number of data types in every programming language. This is true in Kotlin as well.

Furthermore, types in object-oriented programming languages are often divided into primitive and object types. Those available in most languages are Boolean, Int, Char, String and Object/Any types, along with several different number types.

But you won’t always work with only those types. In addition to creating your own types, you often need to work with a large number of objects which are of the same type.

For example, if you’re writing an e-reader application, you’ll display and manage many books. In this case, you have to use a group of objects of the same type. In common terms, this is a collection because you can collect those objects and add or remove them when needed.

But collections aren’t only for storing data. Many programming languages provide different types of collections so you can use them in different scenarios.

Kotlin collections also support this. It provides four different types.

Note: You can open Collections.kt from the Kotlin standard library and take a look at all the Kotlin collections definitions. Most are implemented as interfaces, with concrete implementations varying between each Kotlin collection type.

Collection Types

You can differentiate collections based on a few questions:

  1. Is it dynamic or static in memory?
  2. Does it allow duplicate elements?
  3. How fast is it when it comes to data lookup, insertion or removal?
  4. Can you change the internal contents?

You’ll find the answers to all these questions by exploring the following four collection types:

  1. Array
  2. List
  3. Set
  4. Map

It’s best to start learning about Kotlin collections by exploring arrays since it’s a concept which exists in nearly all programming languages.

Arrays in Kotlin

Array is the simplest Kotlin collection. Here are some points to keep in mind about this collection:

  • It stores objects of the same type together and has a fixed size.
  • It’s a static collection.
  • Each value is indexed by the position in the array.
  • The first value is actually the value with the index zero.
  • The last value is at the index and is equal to the array’s size minus one.

For example, say your computer has thirty blocks of memory free and you create an array of four Int values. The array will take four blocks of the free memory and create one big block of four values, which it groups together.

This means that you can’t add or remove values because the program has allocated that big block to always take four memory slots. But you can always take those four blocks of memory and change what you store in them. Because of this, arrays are immutable when it comes to size, but mutable when it comes to their elements.

Open either the Arrays.kt file or the Kotlin Playground, depending on the work environment you chose, and add the following code:

fun main() {  
  val arrayOfNumbers = arrayOf(2, 3, 5, 6, 10)
  println(arrayOfNumbers)
}

To create an array of any type, all you have to do is call arrayOf(..values). The compiler will know which type of an array it is based on the values you pass in to this method.

In the snippet above, you’ve allocated an array of five numbers, creating an Array of type Int. If you try printing it out by running the snippet of code, you should receive something like [Ljava.lang.Integer;@2b193f2d. Not quite what you expected, right? :]

Since an Array is an object, the output above represents its class name and hash code. To print out the values of an array you have to iterate over them. Change the code above to the following:

fun main() {  
  val arrayOfNumbers = arrayOf(2, 3, 5, 6, 10)
  arrayOfNumbers.forEach { number -> println(number) }
}

Run the code snippet. You should now see the values printed out in the order you created them. Here you used forEach() to iterate through the elements of the array.

Another way you can iterate through the values is by using the Kotlin for loop. Change the forEach(). Change the code above to the following:

fun main() {  
  val arrayOfNumbers = arrayOf(2, 3, 5, 6, 10)
  for (number in arrayOfNumbers) {
    println(number)
  }
}

Run the code and you should see the same output.

There are different ways of creating an array in Kotlin:

  • Create an empty array by calling emptyArray() and specifying the type of the array.
  • Create an array with a specific size, and the default values for all the elements by calling Array(size) { defaultValue }.

For example, if you wanted to create an array with five spots, where each element is an empty String, you’d write the following:

fun main() {  
  val someOtherArray = Array(5) { "" }
  println(someOtherArray)
}

Creating an array is one thing. But you should be able to use its values, access specific indices and change the contents since array contents are mutable.

As previously mentioned, arrays rely on indices. They’re positions in the array memory structure, starting with the zeroth index, for the first item.

Note: This is because computers work with bit registers, and the smallest possible positive number is a zero when all the bits are also zero.

With that in mind, here’s how you’d access the first item in an array:

fun main() {  
  val arrayOfNumbers = arrayOf(2, 3, 5, 6, 10)
  val firstValue = arrayOfNumbers[0] // Resolves to 2
  println(firstValue)
}

You can get items from an array, and almost all the Kotlin collections, by using the square-brackets syntax. Within the brackets, you mention which index you are looking for. In the example above you’d be looking for the zeroth index.

If you try to access a value with an index which is larger than the last index in a collection, or a negative index, you’ll receive an ArrayIndexOutOfBoundsException.

To change a value at a certain index, you can use the same syntax, combined with the assignment operator:

fun main() {  
  val arrayOfNumbers = arrayOf(2, 3, 5, 6, 10)
  val firstValue = arrayOfNumbers[0] // Resolves to 2
  arrayOfNumbers[0] = 100 // the first element of the array is now `100`
  val newFirstValue  = arrayOfNumbers[0]
  println(newFirstValue) 
}

Using the access operator, you can easily change what you store in arrays and access the values.

Note: Re-assignment only works for mutable Kotlin collections. You’ll learn about immutable collections in the next section.

Finally, there’s a plethora of useful functions and properties on arrays, such as array.size to know the size of an array, or array.lastIndex, to know the last index. You’ll cover a lot throughout this tutorial, but the sheer number of functions is baffling! :]

Note: There’s an additional language feature close to arrays called the varags or variable arguments parameter. Be sure to check it out using the official documentation.

Arrays are the basis of all the Kotlin collections because most collections use arrays internally, to store their data. You’ll check it out the next collection.