Kotlin : Use of Collections

Reading Time: 3 minutes

Collections

The Kotlin Standard Library provides a comprehensive set of tools for managing collections – groups of a variable number of items that are significant to the problem being solved and are commonly operated on.

Collections are a common concept for most programming languages, usually containing a number of objects (elements,items) of the same type.

The following collection types are relevant for Kotlin:

  • List is an ordered collection with access to elements by indices – integer numbers that reflect their position. Elements can occur more than once in a list. An example of a list is a telephone number: it’s a group of digits, their order is important, and they can repeat.
  • Set is a collection of unique elements. It reflects the mathematical abstraction of set: a group of objects without repetitions. Generally, the order of set elements has no significance. For example, the numbers on lottery tickets form a set: they are unique, and their order is not important.
  • Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. The values can be duplicates. Maps are useful for storing logical connections between objects, for example, an employee’s ID and their position.

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

List

As a first step in creating a list, Kotlin wants you to declare your intent—immutable or mutable.

  • Mutable List – mutableListOf(),arrayListOf() and ArrayList
  • Immutable List – listOf() and listOf<T>()

The function listOf() returns a reference to an interface kotlin.collections.List . In the following code the reference fruits is of this interface type, specialized to String for the parametric type:

val fruits: List<String> = listOf("Apple", "Banana", "Grape")
println(fruits) //[Apple, Banana, Grape]

To access an element in the list you may use the traditional get() method as well as index operator [], You may check if a value exists in the collection using the contains() method

println("first's ${fruits[0]}, that's ${fruits.get(0)}")
//first's Apple, that's Apple

println(fruits.contains("Apple")) //true
println("Apple" in fruits) //true
fruits.add("Orange") //ERROR: unresolved reference: add

You can create one using the mutableListOf() function. All the operations you were able to perform on List are readily available on the instance of MutableList<T> as well.

val newFruits: MutableList<String> = mutableListOf("Apple", "Banana", "Grape")
newFruits.add("Orange") // It will add an item to the existing list.

Sets

Here we have unordered collections of elements which have both immutable/read-only and mutable/read-write versions, you may create instances of Set using setOf() or instances of MutableSet using mutableSetOf().

val fruits: Set<String> = setOf("Apple", "Banana", "Apple")
println(fruits) //[Apple, Banana]

Just like on List<T> , there are plenty of functions on Set<T> and MutableSet<T> : operations like + , – , contains or in , and so on. The chances are the library already contains a method to accomplish the operation you’d like to carry out on a set. Take time to familiarize with the methods of Set<T> and its mutable
counterpart.

Map

Map<K, V> is not an inheritor of the Collection interface; however, it’s a Kotlin collection type as well. A Map stores key-value pairs (or entries); keys are unique, but different keys can be paired with equal values. The Map interface provides specific functions, such as access to value by key, searching keys and values, and so on.

You may use mapOf() to create a map and get a reference to the read-only interface Map . Alternatively, use mutableMapOf() to get access to MutableMap.

val exampleMap = mapOf("K1" to 11, "K2" to 22, "K3" to 33, "K4" to 44)

println("All keys: ${exampleMap.keys}")
println("All values: ${exampleMap.values}")
if ("k3" in exampleMap) 
    println("Value by key \"k3\": ${exampleMap["k3"]}") 
   
if (11 in exampleMap.values) 
    println("The value 11 is in the map")

if (exampleMap.containsValue(44)) 
    println("The value 44 is in the map")
Output
All keys: [K1, K2, K3, K4]
All values: [11, 22, 33, 44]
Value by key "K3": 33
The value 11 is in the map
The value 44 is in the map

MutableMap is a Map with map-write operations, for example, you can add a new key-value pair or update the value associated with the given key.

val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap.put("three", 3)
numbersMap["one"] = 11

println(numbersMap) // {one=11, two=2, three=3}

Want to learn more on List, Sets, Map.
For more tech blogs, please visit Knoldus Blogs.

Written by 

Hi, I am a Software Intern in Knoldus Inc. with experience in technologies like Java Programming, SpringBoot. I am always ready to learn new technologies. My hobbies are watching web series and playing games.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading