Collections in Kotlin

Introduction

Collections play a crucial role in software development, allowing us to efficiently manage and manipulate groups of data. In Kotlin, a modern and expressive programming language, the collection framework offers a rich set of tools and types for working with data in a flexible and concise manner. This article explores the several types of collections in Kotlin, including arrays, lists, sets, maps, and sequences.

Kotlin Collections 

It all starts with storing data; storing data of the same type is the common concept behind the evolution of collection in the Programming world. These days, this fundamental idea is included in the majority of programming languages.

A Collection is a group of the same type of objects or items, like a list of workers or a set of mangoes. Now the workers can be unique, or the mangoes can be of the same type. We can draw them to distribute the salary or put them in unorder, likely in case of putting mangoes in the store. These are a few widespread applications of data storage that may be found worldwide. The collecting concept used here follows the same logic.

Collections in Kotlin

In Kotlin, there is a dedicated standard library of tools for collection. We'll focus on the most popular tools in the field that are crucial to you. The following are some of the most used collection types in kotlin:

  • List: is a collection type that has ordered element and allow duplicated types of element. Ex.- list of movies, actors, etc.

  • Set: is a collection type that only can contain elements of unique value. Ex.- set of colors, set of directions, etc.

  • Map: Maps or dictionary is a collection type that is available in terms of key-value pairs. Each key is unique, but the value can be duplicated. Ex. a collection of employees in a company.

  • Array: An array is the same as a list; the only difference is that an array's size is defined upon initialization and is never changed.

  • Sequences:  A sequence in Kotlin is a particular collection that depicts a series of components. A sequence is evaluated lazily, as opposed to lists or sets, which means that elements are only computed when needed. The processing of enormous or endless data sets is made more effective by this lazy evaluation.

The collection interfaces and related functions are located in the kotlin.collections package. Let's get an overview of its contents.

Types of Collection in Kotlin

The Standard library of Kotlin has classes and interfaces for the basic type of collections like lists, sets, and maps. Unlike other languages in Kotlin, there is a pair of interfaces representing of type:

  • Immutable or read-only- These interface has all the operations for only accessing the elements in collections.
  • Mutable- A mutable interface has read with write operations to perform, like adding, removing, and updating elements.

Note - declaring collection with val doesn't affect read or write operation, but actually, it will give you compile error when trying to reassign a val collection.

val myList = mutableListOf(1,2,3,4)
myList.add(5)   // this is OK
println(myList)
//myList = mutableListOf(6,7)      // compilation error

Here is the diagram of collection interfaces in Kotlin:

Collections in Kotlin

Let's walk through each to learn about Arrays, ListsSets, and Maps

Arrays

Array in kotlin, like other languages, is the most common fundamental block of storing data. It is represented by the Array class. It has to get() and set() functions that have operator overloading by "[ ]".  

To create an array, use the function arrayOf() and pass the item values to it so that arrayOf(1, 2, 3) creates an array [1, 2, 3]. Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements. Let's see how we can define an array in multiple types and print what class it is using.

    val arr = Array(5) { i -> (i * i).toString() }
    val arr1 = intArrayOf(0,1,4,9,16)
    val arr2 = arrayOf(0,1,4,9,16)
    val arr3 = arrayListOf(0,1,4,9,16)

    arr.forEach { print( it+" ") }
    println("\nLet's print out the type")
    println(arr.javaClass)
    println(arr1.javaClass)
    println(arr2.javaClass)
    println(arr3.javaClass)

Output

Collections in Kotlin

Lists

Let's start with the most popular candidate of a collection in kotlin, which is a list; you probably already have an intuitive understanding of what a list is but let's just rehearse it for a second. A list is an ordered collection of elements that allows duplicates. So what does that mean? It just means that you can access the elements of a list using indices, so you can say give me the element at position 2. In Kotlin, you can create a list using the listOf() function or the mutableListOf() function for a mutable list. Lists provide various operations such as adding, removing, and accessing elements by index. They also support functions like filter, map, and reduce for data transformation and aggregation.

    val numbers = listOf(1, 2, 3, 4, 5)
    val mutableList = mutableListOf("apple", "banana", "orange","apple")

    println(mutableList[2])
    mutableList.forEach {
        println("Current element is ${it}")
    }

Output

Sets

Sets are groups of objects where we don't care so much about the order of elements. Instead, we want to ensure that our collection never contains duplicates. That's the key property of a set. All of the contents are unique makes sets a bit more of a specialized data structure. So A Set is a collection that contains unique elements with no defined order.

There's a good chance you want to use them in everyday scenarios anyway because what are typical things you might want to store in a set of tags for example, you want to make a list of all tasks according to the seven days of the week and also make a list of the task according to their importance low, medium and high in both cases having duplicates in these collections doesn't really make a lot of sense, and the order also doesn't really matter.

Kotlin provides setOf() and mutableSetOf() functions for creating sets. Sets support operations like adding and removing elements. They also provide set-specific operations like union, intersection, and difference.

    val uniqueNumbers = setOf(1, 2, 3, 4, 5)
    val mutableSet = mutableSetOf("monday", "tuesday", "wednesday","thursday","friday","saturday","Sunday")

    println(mutableSet.elementAt(2))

    mutableSet.forEach {
        println("Current day is  $it")
    }

Output

Collections in Kotlin

Maps

A map is a collection that associates keys with values. Each key in a map must be unique. It's also sometimes referred to as a dictionary for that reason. We encounter maps whenever we are associating data storing a person's name and their favorite pizza topping or associating a license plate with vehicle information key-value pairs are everywhere and just like many other languages. Maps are the go-to way to manage them in kotlin.

You can create a map using the mapOf() function or the mutableMapOf() function for a mutable map. Maps provide operations to add, update, and remove key-value pairs. They also support functions like keys, values, and entries to access different parts of the map.

    val numberMap = mapOf("one" to 1, "two" to 2, "three" to 3)
    val mutableMap = mutableMapOf("name" to "John", "age" to 30)

    println(numberMap.get("name"))

    mutableMap.forEach {
        println(it)
    }

Output

Collections in Kotlin

Sequences

In Kotlin, a sequence is a type of collection that represents a series of elements, similar to a list or an array. However, sequences are evaluated lazily, meaning elements are computed only when needed. This lazy evaluation can provide performance benefits when working with large or infinite data collections.

    val numbers = sequenceOf(1, 2, 3, 4, 5)

    val filteredSequence = numbers.filter { it % 2 == 0 } // Lazily filters even numbers
    val doubledSequence = filteredSequence.map { it * 2 } // Lazily doubles each element

    println(filteredSequence.toList()) // Forces evaluation and prints [2, 4]
    println(doubledSequence.toList()) // Forces evaluation and prints [4, 8]

Output

Collections in Kotlin

Conclusion

In conclusion, Kotlin's collection structure gives programmers a flexible toolkit for efficiently maintaining and processing data. By utilizing arrays, lists, sets, maps, and sequences, we may meet various programming requirements and enhance the readability and efficiency of our code. Lists offer ordered and mutable collections, whereas arrays give a simple fixed-size collection. While maps allow for key-value associations, sets guarantee uniqueness and are capable of set-specific operations.

Finally, sequences enable the efficient processing of huge or infinite collections through lazy evaluation. Developers can manage data in a more expressive and effective way by being aware of these collection kinds and their corresponding operations. We can confidently handle data manipulation tasks with beauty and performance using Kotlin's collection structure, maximizing the potential of our code. Hope this has been a helpful guide for you, do not forget to write your views about this article in the comments. Thank you!

FAQ's

Some possible questions & answers related to Collection in Kotlin include,

Collections in Kotlin FAQs

Q. What is the difference between a list and a set in Kotlin?

A. A list is an ordered collection that allows duplicates, while a set is an unordered collection that ensures the uniqueness of elements.

Q. How can you add elements to a mutable list in Kotlin?

A. You can use the add() function to add elements to a mutable list, or the addAll() function to add multiple elements at once.

Q. What advantage do sequences offer over regular collections in Kotlin?

A. Sequences provide lazy evaluation, allowing for efficient processing of large or infinite collections by computing elements only when needed.

Q. How can you iterate over the key-value pairs of a map in Kotlin?

A. You can use the forEach function with a lambda expression to iterate over the entries of a map and perform operations on each key-value pair.

Q. What is the benefit of using an array over a list in Kotlin?

A. Arrays have a fixed size, which can be advantageous when you know the exact number of elements in advance or require a more memory-efficient representation.

Some other important articles on Kotlin


Similar Articles