Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

What are Kotlin Collections?

Victor Adedeji

kotlin

Collection means a set of items or number of materials procured or gathered together as one.

Collections of teddy bears
Collections of teddy bears

Collection in programming is a term used to represent a set of similar data type items and class them as a single unit. This takes into consideration the underlying data structures that help with efficient manipulations and storage.
In this writeup, we are going to try to understand:

  • What are Kotlin collections?
  • What are the types of Kotlin collections?
  • What do they do?
  • When should you use any of these types of collections?

Collections are part of Kotlin’s standard library package, kotlin.collections, which includes all the essentials functions of Kotlin operations. The Kotlin language is totally interoperable with Java; therefore, you can call Kotlin code from Java and vice versa. You can also use all the collections that are available in Java with Kotlin.

The Three Types of Kotlin Basic Collections:

  • List - is an interface derived from the collection, it is an ordered collection of elements.

  • Set - is also an interface that is derived from the collection. It is an unordered collection of elements that don’t allow duplicate elements to be present. In other words, it is a collection of unique elements in which the order is of no significance.

  • Map - It is a set of key-value pairs with a set of unique keys. It can have duplicated values.

Kotlin collections are categorically in two distinct forms:

  1. Immutable Collection: this term implies that these functionalities support read-only access and cannot make any modification to objects or elements.

  2. Mutable Collection: this term implies that the functionalities support both read and write and can, therefore, modify objects or elements.

The Kotlin basic collection type can decide to exhibit both read-onlyImmutable and mutable forms.

Create list in Kotlin

You can create a mutable or immutable list with Kotlin. You just need to indicate the type, e.g., you create an immutable list with the keyword listOf() while you use mutableListOf() to create a mutable list.

Let’s write some code:


fun main(){
  // create an immutable list
  val cars:List<String> = listOf("Tesla","Honda","BMW","Benz");
println("an Immutable list")
println(cars)

}

The code above creates an immutable list of cars. Next, we try to perform some operations on it, such as accessing the elements and writing to modify the list.


fun main(){
  // create an immutable list
  val cars:List<String> = listOf("Tesla","Honda","BMW","Benz")
  println("car at index 0 is ${cars[0]}")

  // add to the list
  cars.add("Apple Car")
  println(cars)
}

If you try to compile the above code you will get the following error :
error: unresolved reference: add

The add method is meant to modify and include a new element to the list of cars. However, the reference type isn’t mutable, which results in an error.

fun main(){
  // create an mutable list
  val cars: MutableList<String> = mutableListOf("Tesla","Honda","BMW","Benz")
  println("car at index 0 is ${cars[0]}")

  // add to the list
  cars.add("Apple Car")

  // add a new car at index 0
  cars.add(0, "Audi")
  println("car at index 0 is ${cars[0]}")
  println(cars)
}

You can see in the code above that the mutableListOf() function takes in a list that can be modified at anytime. The apple car was added to the list of cars without any issue or error, and the Audi car was inserted at index 0.

It is important to always decide what type of list you want to work with while writing Kotlin. listOf() references the kotlin.collections.List<T> interface, whereas mutableListOf() returns a reference to the interface MutableList<T>.

Set in Kotlin

Kotlin immutable set can be created with the setOf() function. This function creates a read-only reference of the Set<T> type interface; whereas mutableSetOf() is used to create a reference of the interface MutableSet<T>.

Let’s code it!

fun main(){
    // Immutable Set
    val subjects:Set<String> = setOf("English","Mathematics","Physics","Computer Science","English")
    println(subjects)
  
}

In the code above, an immutable set of subjects was created, with English appearing twice. Kotlin Set will not repeat the value because it only returns unique values, which is why the code prints out
[English, Mathematics, Physics, Computer Science] and not
[English, Mathematics, Physics, Computer Science, English].

However, if you try to add a new subject to the code above, it will result in an error. Next, we will see how to create a mutable set in Kotlin.

fun main(){
    // Mutable Set
    val subject:MutableSet<String> = mutableSetOf("English","Mathematics","Physics","Computer Science")
    println(subject)

    subject.add("Chemistry")
    subject.add("Economics")

    println(subject)

  
}

The code above creates an Immutable set of subjects with the mutableSetOf() function, which enhances it to add new subjects without resulting in an error.

You can find all the operation Kotlin set support here.

Kotlin map

A map is a set of key-value pairs, with a set of unique keys that can have duplicated values. Maps are useful when you want to look up values by means of an identifier.

For example, if you want to get the number of goals a football player has scored, then the best way to store them would be to use a map:

  • Key= the players name
  • Value = the number of goals he has scored

Let’s put this into code.

fun main(){
    val trackGoals = mapOf("Balo " to  4,"Bolaji" to 2, "Samuel" to 3)
    println(trackGoals)
    // Get the score of Balo
    println(trackGoals.get("Balo"))
    // loop through and print out the  
    for (track in trackGoals){
        println(track)
    }
}

The code above creates a map to store the numbers of goals each player scores. It then uses the get operation method to get the score of any player whose goal has been recorded.
However, you won’t be able to add new players score to the data because the reference type interface of mapOf() is a read-only interface Map<K, V>.

Instead, you need to use the mutableMapOf() method type reference to update the data with the new player name and goals.

fun main(){
    val trackGoals = mutableMapOf("Balo" to 4, "Bolaji" to 2, "Samuel" to 3)
    println(" Initial Score Track Data\n $trackGoals \n")
    // add new player info to the data
   trackGoals.put("Messi",10)
   trackGoals.put("John",7)
   println("New Score Track Data \n $trackGoals")
}

The code above creates a mutable map and then modifies the existing data by adding new players with their corresponding scores.

You can find all the operation Kotlin map support here.

When do you use List, Set, or Map in Kotlin?

  1. List is an ordered collection; therefore, if there’s going to be a regular search or insertion operations based on the index values, it is best to use a List.

  2. Set, unlike a list, is an unordered collection with unique elements; so, you should first think of Set if you don’t want duplicative values or items in your database.

  3. Map is a set of key-value pairs with unique keys that can have duplicated values. It is also an unordered collection; so, for example, if you want your database to exhibit key and value mapping, use Map.

RELATED TAGS

kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring