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ć.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Kotlin Collections: Getting Started
30 mins
- Getting Started
- What are Collections?
- Collection Types
- Arrays in Kotlin
- Creating An Array
- Working With Arrays
- Lists in Kotlin
- Creating a List
- Mutable Lists
- Sets in Kotlin
- Creating Sets
- Working With Sets
- Maps in Kotlin
- Creating a Map
- Working With a Map
- Concrete Collection Types
- Collection Operators
- Transforming Data
- Filtering and Grouping Data
- Validating Data
- Looking Up Data
- Where To Go From Here
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.
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.
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.
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:
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.
Collection Types
You can differentiate collections based on a few questions:
- Is it dynamic or static in memory?
- Does it allow duplicate elements?
- How fast is it when it comes to data lookup, insertion or removal?
- Can you change the internal contents?
You’ll find the answers to all these questions by exploring the following four collection types:
- Array
- List
- Set
- 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.
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.
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! :]
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.