'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Jun 30, 2023

Kotlin Collections

Author Pradeep Kumar
1 upvote
gp-icon
Fundamentals of react native
Free guided path
7 chapters
15+ problems
gp-badge
Earn badges and level up

Introduction

In this blog, we will discuss Collections in Kotlin. Collections in Kotlin are used to store a group of related objects in a single unit. We can store, retrieve, manipulate, and aggregate data by using collections. We will also see different types of collections: Mutable Collections and Immutable Collections.

We will also look at Mutable and Immutable types of listssets, and maps. We will see how each one of these collections can be initialized. In the next section, we will study collections.

Collections

A collection contains a number of objects of the same data type. Objects in a collection are generally called elements or items. For example, all the employees in a company form a collection that can be used to calculate their average salary.

In Kotlin, Collections are of two types, which are as follows:

  1. Immutable Collection
  2. Mutable Collection

Immutable Collections

Immutable Collections only support read-only operations. Once initialized, you can not add or remove elements from the collection

Different types of immutable collections are:  

  • List 
  • Set
  • Map

List

The list is an ordered collection in which we can access any element by its index. In a list, elements can be repeated any number of times. The immutable list does not allow us to add or remove items. You can use the listOf() method to initialize an immutable list.

In the example below, we will see how an immutable list can be initialized and how we can print the elements of it:

// Function to print the elements of an immutable list
fun main(){
    // Initialising a list 
    val numList = listOf(1,2,3,4,"a","b")
    for(num in numList){
        println(num)
    }
}

Output:

1
2
3
4
a
b

Set

Set is a collection of unordered elements. It doesn’t support duplicate elements; therefore, all the elements in a set are unique. In most cases, the order of set elements does not have a substantial impact. As it is an immutable set, we can not perform add or remove operations.

setOf() method can be used to initialize an immutable set.

In the example below, we will see how we can declare an immutable set.

// Function to print the elements of an immutable set
fun main(){
    // Initialising a set
    val numSet = setOf(1,2,3,4,4,3,"a","b","c","d","d")
    for(num in numSet){
        println(num)
    }
}

Output:

1
2
3
4
a
b
c
d

As you can see from the above example, even though we added duplicate elements while making the set, we only see unique elements while printing the elements. An immutable set doesn’t store duplicate elements.

Map

Elements of a map are stored as key-value pairs. Each key maps exactly to one value. Keys are unique, but values can be the same for two keys. As it is an immutable map, you can not add or remove elements once initialized. To initialize an immutable map, you can use the method mapOf(). For example,

// Function to print the elements of an immutable map
fun main(){
    // Initialising a map
    val numMap = mapOf(97 to "a", 98 to "b", 99 to "c", 100 to "d", 101 to "e")
    for((key,value) in numMap){
        // printing key value pair
        println("key: $key, value: $value")
    }
}

Output:

key: 97, value: a
key: 98, value: b
key: 99, value: c
key: 100, value: d
key: 101, value: e

Mutable Collections

mutable collection supports both read and write operations. We can add or remove elements from a mutable collection. Different types of mutable collections are:  

  • Mutable List 
  • Mutable Set 
  • Mutable Map

Mutable List

It is similar to an immutable list, but you can also add or remove elements from a mutable list. You can use the method mutableListOf() to initilze a mutable list. A program to demonstrate the functioning of a mutable list:

// Function to print the elements of an Mutable list
fun main(){
    // Initialising a Mutable list
    val numList = mutableListOf<Int>(1,2,3,4,)
    numList[2]=5; // changing element at index 2 to 5
    numList.remove(4) // removing element with value 4
    for(num in numList){
        println(num)
    }
}

Output:

1
2
5

Mutable Set

mutable set supports both read and write operations. Elements or items can be added to or removed from a mutable set, and the order of elements will be preserved. mutableSetOf() method can be used to instantiate a Mutable Set.  For example,

// Function to print the elements of an Mutable set
fun main(){
    // Initialising a set
    val numSet = mutableSetOf(1,2)
    numSet.add(3) // adding 3 to the set
    numSet.remove(2) //removing 2 from the set
    for(num in numSet){
        println(num)
    }
}

Output:

1
3

Mutable Map

It is similar to an immutable map; it also supports functionalities like - put, remove, and clear to support adding and removing elements in a map.To initialize a mutable map, you can use the method mutableMapOf(). For example,

// Function to print the elements of an Mutable map
fun main(){
    // Initialising a map
    val numMap = mutableMapOf<Int,String>(97 to "a", 98 to "b", 99 to "c", 100 to "d", 101 to "e")
    numMap.put(102,"f") // Putting new element with key 102 and value "f"
    numMap.remove(98) // Removing element with key 98
    for((key,value) in numMap){
        // printing key value pair
        println("key: $key, value: $value")
    }
}

Output:

key: 97, value: a
key: 99, value: c
key: 100, value: d
key: 101, value: e
key: 102, value: f
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FAQs

  1. Can you add an element of string type in a mutable Set of integer types?
    No. You can not add elements of another type in a mutable set. All the elements in a mutable Set should be of the same type. But in the immutable set, elements can be of different types.
     
  2. What will happen if you remove an element from a Mutable list that is present more than once in the list?
    Upon removing an element that has multiple occurrences in the list, it will only remove the first occurrence of the element.
     
  3. How can you remove an element from a Mutable map?
    To remove an element from a mutable map, you can pass the key or the key-value pair to the remove function. If you are passing a key-value pair, the element will only get deleted if the value given is associated with the key.

Key Takeaways  

Cheers if you reached here!!!

In this blog, we discussed collections and their types: Mutable Collections and Immutable Collections. We also looked at both mutable and immutable types of listssets, and maps. Additionally, we saw how they could be initialized and edited (in case of mutable collections). 

After reading this blog, I believe you will be able to work with Kotlin Collections smoothly. If you wish to know how we can iterate over these collections using loops, you can check our other article Kotlin Loops on the Coding Ninjas Website. And to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website. 

Next article
Kotlin Lists and Mutable Array
Guided path
Free
gridgp-icon
Fundamentals of react native
7 chapters
15+ Problems
gp-badge
Earn badges and level up
Live masterclass