Kotlin Collections and Arrays

In this tutorial, we are going to talk about arrays, collections and other Data structures supported by Kotlin.

Arrays

In Kotlin, arrays are only types, more specifically, arrays are parameterized arrays. For example if we wish to create an array of integers, the following snippets may work

var names = arrayOf (1,101,1001,201,301)

Kotlin provides library functions such as arrayOf, emptyArray, and arrayOfNulls which are used to create arrays.

emptyArray function to create an array

var arr = emptyArray<String>();
arr += "one"
arr += "two"
arr += "three"

above is useful to create an empty array, later items can be added in array using +=.

arrayOfNulls Function to create array

var arr = arrayOfNulls<String>(2)
    arr.set(0, "one")
    arr.set(1, "two")

above will create a null array of size 2, later items can be added using set method.

arrayOf Function to create array

var words = arrayOf("cat", "rat", "set")

above will create an array of words using arrayOf function for 3 string values

Array Constructor to create array

var ints    = Array <Int> (3, {it})
var strings = Array<String> (3, {it.toString()})

In above code snippets, Array constructor takes in two arguments, the 1st argument defines the size of the array to be created and the 2nd argument is a lambda function that can return an initial value of each element.

Though, special classes like ByteArray, IntArray, ShortArray, and LongArray represent arrays of primitive types (like Java). These special classes allows us to work with arrays without the burden of boxing and unboxing that is used by Array

Example of Special Array Types

var p = intArrayOf(1,2,3,4)
var q = longArrayOf(1,2,3,4)

var r = byteArrayOf(1,2,3,4)
var s = shortArrayOf(1,2,3,4)

Collection

A collection is a group of elements that are related to one another, such as a list of words or a set of employee records. The pieces in the collection might be arranged or unordered, and they can be unique or not.

A collection is often made up of a number of objects of the same type (this number can be zero).
Elements or items refer to the objects in a collection.

Kotlin supports the following collections:

  • List
  • Set
  • Map

Kotlin does not support any dedicated syntax for creating lists or sets, but it provides library functions to create various collections.

Collections and their Creation Functions

CollectionRead-OnlyMutable
listlistOfmutableListOf, arrayListOf
setsetOfmutableSetOf, hashSetOf, linkedSetOf, sortedSetOf
mapmapOfmutableMapOf, hashMapOf, linkedMapOf, sortedMapOf

List

List is a collection of order elements which is accessed using an index (an integer number that reflects the position of each element in the collection). Like an array, it is a zero based collection of elements.

Example to create a list using listOf() function

// www.raviroza.com
// 27-Jan-2022, 5.18 pm
fun main()
{
    // creating read-only list with listOf
    var readOnlyList = listOf("C","C++","C#","Java","Kotlin","www.raviroza.com")

    println("Display - using println")
    println(readOnlyList)

    println()
    println("Display - using For loop")
    for (a in readOnlyList)
    {
        println(a)
    }

}

Above example creates a read only list with listOf() function, read-only does not allow modifying the list.

Example to create a mutable list (editable list) using mutableListOf() function

// www.raviroza.com
// 27-Jan-2022, 5.18 pm
fun main()
{
    // creating Mutable List with mutableListOf
    var mutableList = mutableListOf ("C","C++","C#","Java")


    println("Display - using println")
    println(mutableList)


    // methods to modify the list as it is a mutable list
    mutableList.set(0,"C Lang.")
    mutableList.add(2,"Swift")
    mutableList.add("Kotlin")
    mutableList.add("www.raviroza.com")

    mutableList.remove("C Lang.")
    mutableList.removeAt(2)

    println()
    println("Display - using For loop")

    for (a in mutableList)
    {
        println(a)
    }
    println(mutableList)
}

Above example creates a mutable list, it does allow us to add, modify or delete elements from the list.

List of important methods of mutable list

MethodDescription
add()adds an element in list
remove(“item name”)remove an element specified by item name
removeAt()removes an elements specified by index
first()returns the first element from the list
last()returns the last element from the list

Sets

Sets and lists are similar in structure and operation, so whatever we’ve learned about lists also applies to sets.

Sets differ from lists in that they apply restrictions on element uniqueness. They don’t allow duplicate elements or the same elements within a set.

Example to create a unique sets of characters, numbers and string

// www.raviroza.com
// 27-Jan-2022, 5.55 pm
fun main()
{
    var cities = mutableSetOf("Jam","Raj")

    println("Cities - mutable set")
    cities.add("Jam")
    cities.add("Raj")
    cities.add("Ahm")

    println(cities)

    // creating mutable set of numbers using range
    val numbers = (1..25).toMutableSet()

    // it removes the element with odd indices
    numbers.removeIf { i -> i % 2 == 1 }

    println("\nNumbers - mutable set")
    println(numbers)


    // creating mutable set of chars using range
    val chars = ('a'..'f').toMutableSet()
    println("\nCharacters - mutable set")
    println(chars)
}

In the above example, the cities set is created using mutableSetOf() function, though it allows us to add items to the cities set, but won’t accept the elements that already exist.

We can also create a mutable set using the range (..) operator. Here, we have created two mutable sets using the range operator that is numbers and chars.

Maps

Maps, unlike lists and sets, are made up of pairs of values rather than single values. It is similar to the HashTable in Java.

A map is like a dictionary or a phone book. Its contents are organized using a key-value pair. For each key in a map, there is one and only one corresponding value.

Example to create read only map and mutable map.

// www.raviroza.com
// 27-Jan-22, 6.37 pm
fun main()
{
    // to create read only map
    val phoneBook = mapOf (1 to "ravi",2 to "amit")
    println(phoneBook)

    println(phoneBook.get(1))

    // to define mutable map from read only map
    var pb = phoneBook.toMutableMap()

    // add new element in hash map as it is mutable now
    pb[3] = "raviroza.com"

    pb.put(4,"all in one")

    // display using println
    println(pb)

    // display using for loop
    for(x in pb)
    {
        println(x)
    }
}

Common Operations on Collections

Function or PropertyDescription
Sizetells the number of elements in the collection (lists, sets and maps).
isEmpty()returns true if the collection is empty, False otherwise (lists, sets, and maps).
contains(arg)returns true if arg is within the collection (lists, sets, and maps).
add(arg)add arg to the collection. this function returns true if arg was added
– in the case of a list, arg will always be added.
– in the case of a set, arg will be added and return true the first time
remove(arg)returns true if arg was removed from the collection, returns False otherwise
iterator()returns an iterator over the elements of the object (lists, sets, and maps).

Collection Traversal

Like Java, Kotlin does also provide the iterators to go through the elements of the collection.

fun main()
{
    val fruits = listOf("Apple", "Grapes", "Banana", "Brange")

    var iter = fruits.iterator()

    println("Display - using iterator")
    // while loop to iterate through elements
    while (iter.hasNext())
    {
        println(iter.next())
    }

    // for loop to iterate though elements
    println("\nDisplay - for loop")
    for (i in fruits)
    {
        println(i)
    }
}