
Kotlin Collections help us to store a group of objects in a single variable. In this article, we will explore collections with examples.
Prerequisites:
What are Kotlin Collections?
Kotlin collections are used to store a group of objects in a single variable. The objects are called elements (or items). Typically, they are of the same data type.
There are 3 types of collections in Kotlin:
- List
- Set
- Map (or Dictionary)
Each collection is categorized into two types – immutable and mutable.
Immutable Collection:
The immutable collection only supports read operations. We cannot modify the elements. As a result, it has a fixed size. Once we created an immutable collection, we cannot add or remove elements.
Mutable Collection:
The mutable collection supports both read and write operations. We can update, delete, and add new elements.
Kotlin provides different methods in each collection:
Collection Type | Methods |
List | Immutable List: listOf() Mutable List: arrayListOf() mutableListOf() ArrayList() |
Set | Immutable Set: setOf() Mutable Set: mutableSetOf() hashSetOf() |
Map | Immutable Map: mapOf() Mutable Map: mutableMapOf() hashMapOf() HashMap() |
Note: The collection interfaces and related functions are available in the kotlin.collections package.
Now, let us understand each collection with examples.
List:
A List is a group of elements of the same or different data type. Each element can occur more than once.
Immutable List:
We can use the listOf() method to create an immutable list.
val myNumbers = listOf(10, 30, 50, 10, 40)
Here, myNumbers is a list, and 10, 30, 50, 10, 40 are elements. To access them, use the get() method or square brackets with the index.
fun main() {
val myNumbers = listOf(10, 30, 50, 10, 40)
// Using index
println( myNumbers[0] ) // prints 10
// Using get() method
println( myNumbers.get(0) ) // prints 10
}
Note: The index in any collection starts from 0.
To get all the elements, we can use for loop with in operator.
fun main() {
val myNumbers = listOf<Int>(10, 30, 50, 10, 40)
for (element in myNumbers) {
println(element)
}
}
Output:
10
30
50
10
40
Mutable List:
If you think you will update the list later in the code, declare a mutable list. We can use arrayListOf() and mutableListOf() methods to create the mutable list. Both of these methods return an ArrayList object. We can also use the ArrayList constructor to create the list as well. We will discuss it in a moment.
fun main() {
// Using mutableListOf()
val list1 = mutableListOf<Int>(10, 40, 89, 10)
// Using arrayListOf()
val list2 = arrayListOf<Float>(10.3f, 40.2f, 89.0f, 10.3f)
}
We can access elements with the get() method or square brackets with an index. If you want to print all the elements, use the for loop with the in operator.
fun main() {
val list1 = mutableListOf<Int>(10, 40, 89, 10)
// Using the index
println("Using index: " + list1[1])
// Using the get() method
println("using get() method: " + list1.get(1))
// Printing all the elements
println("All elements:")
for (number in list1) {
println(number)
}
}
Output:
Using index: 40
using get() method: 40
All elements:
10
40
89
10
Updating Mutable List:
Kotlin provides built-in methods to update the list.
add(element: E) – Adds a new element at the end of the list
add(index: Int, element: E) – Adds a new element at the index.
remove(element: E) – Removes the element
removeAt(index: Int) – Removes the element at the given index
Here E represents the type of element (like Int, String, Float, etc.)
Example:
fun main() {
val list1 = mutableListOf<Int>(10, 40, 89, 10)
// adds 30 at the end of the list
list1.add(30)
println("Adding 30: $list1")
// adds 20 at index 1 (before 40)
list1.add(1, 20)
println("Adding 20: $list1")
// removes the 10
list1.remove(10)
println("Removing 10: $list1")
// removes the element at index 2
list1.removeAt(2)
println("Removing the element at index 2: $list1")
// updating the first element
list1[0] = 200
println("Updating the first element: $list1")
}
Output:
Adding 30: [10, 40, 89, 10, 30]
Adding 20: [10, 20, 40, 89, 10, 30]
Removing 10: [20, 40, 89, 10, 30]
Removing the element at index 2: [20, 40, 10, 30]
Updating the first element: [200, 40, 10, 30]
We can also initialize an empty list and add elements later.
fun main() {
val list1 = mutableListOf<Int>()
list1.add(20)
list1.add(40)
list1.add(210)
println(list1) // prints [20, 40, 210]
}
We can also create a list using the ArrayList constructor. But, it doesn’t accept elements. We need to add them after the initialization.
fun main() {
val list1 = ArrayList<Int>()
list1.add(300)
list1.add(500)
println(list1) // prints [300, 500]
}
Set:
Set is a group of objects but the objects should be unique. Set removes the repeated elements automatically. Generally, the order of Set elements has no significance.
Immutable Set:
Use setOf() function to create an immutable set.
fun main() {
val set1 = setOf(20, 30, 10, 20, 30, 50)
println(set1) // prints [20, 30, 10, 50]
}
Accessing Set Elements:
Use the elementAt() method to access the set elements.
fun main() {
val myNumbers = setOf<Int>(10, 30, 50, 10, 40)
val firstElement = myNumbers.elementAt(index = 0)
println("First Element: $firstElement")
println("Printing All Elements:")
for (element in myNumbers) {
println(element)
}
}
Output:
First Element: 10
Printing All Elements:
10
30
50
40
Mutable Set:
We can create a mutable set using the mutableSetOf() and hashSetOf() methods.
fun main() {
println("*** Using mutableSetOf() ***")
val mutableSet1 = mutableSetOf<Int>(20, 30, 40)
println("First Element: ${mutableSet1.elementAt(0)}")
println("Printing All Elements:")
for (element in mutableSet1) {
println(element)
}
println("*** Using hashSetOf() ***")
val hashSet1 = hashSetOf<Int>(200, 300, 400)
println("First Element: ${hashSet1.elementAt(0)}")
println("Printing All Elements:")
for (element in hashSet1) {
println(element)
}
}
Output:
*** Using mutableSetOf() ***
First Element: 20
Printing All Elements:
20
30
40
*** Using hashSetOf() ***
First Element: 200
Printing All Elements:
200
400
300
Updating Mutable Set:
fun main() {
val set1 = mutableSetOf<Int>()
// adding elements
set1.add(10)
set1.add(20)
set1.add(30)
println("Set: $set1")
// removes 20
set1.remove(20)
println("Removing 20: $set1")
}
Output:
Set: [10, 20, 30]
Removing 20: [10, 30]
Map:
A map is a group of key-value pairs. The keys should be unique. Both the keys and values can be of any data type.
Immutable Map:
Kotlin provides mapOf() to create an immutable map.
val myMap = mapOf<Int, String>(1 to "Apple", 2 to "Mango", 3 to "Watermelon")
Here, 1, 2, 3 are keys, and Apple, Mango, and Watermelon are values.
Reading Map Keys and Values:
There are different ways to access map elements.
get(key: K) – The method accepts a key and returns the corresponding value. If the key is not found, it returns null.
mapObject.keys and mapObject.values – They return keys and values in the given Map respectively. The return type is Set.
We can also use square brackets to get the values.
Example:
fun main() {
val myMap = mapOf<Int, String>(10 to "Ten", 20 to "Twenty", 30 to "Thirty")
println("myMap.get(30) = ${myMap.get(30)}")
println("myMap[20] = ${myMap[20]}")
println("*** Keys ***")
for (key in myMap.keys) {
println(key)
}
println("*** Values ***")
for (value in myMap.values) {
println(value)
}
}
Output:
myMap.get(30) = Thirty
myMap[20] = Twenty
*** Keys ***
10
20
30
*** Values ***
Ten
Twenty
Thirty
Mutable Map:
mutableMapOf(), hashMapOf(), and HashMap() are used to create mutable map.
fun main() {
val map1 = mutableMapOf<Char, Int>('a' to 100, 'b' to 200)
val map2 = hashMapOf<String, Float>("First" to 1.0f, "Second" to 2.0f)
val map3 = HashMap<Int, Int>()
}
Updating Map Elements:
fun main() {
val map1 = mutableMapOf<Char, Int>('a' to 100, 'b' to 200)
map1.put(key = 'c', value = 300)
println(map1) // prints {a=100, b=200, c=300}
map1.replace('a', 500)
println(map1) // prints {a=500, b=200, c=300}
map1.remove(key = 'c')
println(map1) // prints {a=500, b=200}
}
This is all about Collections in Kotlin. I hope you have learned something new. If you have any doubts, comment below.
References: