Kotlin Tutorial - 4 Built-in Data Structures

There are many built-in data structures that can be used in Kotlin including Array, List, Set and Map. These built-in data structures is also known as Collections.

Array

Array is a data structure that could store many items with the same type or with different data types. Array is mainly used to store many items with the exact amount.

Array data structure is illustrated in this picture below.

This is the basic syntax of creating array.

// with initialised items
val variable_name = arrayOf(items)

// for specific data type
val variable_name = data_typeArrayOf()
//example: for Int items only
val items = intArrayOf()

// create empty or null array
val variable_name = arrayOfNulls<data_type>(array_size)

This is the example of array usage.

fun main() {
    // create an array of strings
    val items = arrayOf("Java","PHP","Go","NodeJS")

    // change or set the item at index 1
    items[1] = "Kotlin"

    // get the item at index 2
    println("Item at index 2: ${items[2]}")

    // prints out the items inside array
    for (item in items) {
        println(item)
    }
}

Output

Item at index 2: Go
Java
Kotlin
Go
NodeJS

Based on the code above, the array is used to store many String items. To change or access the item from array can be done by using [] (square brackets). The item at index 1 is changed with Kotlin then the item at index 2 is printed out. The item at index 2 is Go because the index of array started at index 0 so the item that located at index 2 is Go. All of the items inside array is printed out using for loop.

For collections type, use [] for set or get operations. (Except Set)

List

List is a data type that can be be used to store many items with same type or different data types. List is suitable to store many items with unexact amount.

This is the basic syntax of creating list.

// with initialised value (read only)
val variable_name = listOf(items)

// create mutable list with empty value
val variable_name = mutableListOf<data_type>()

// create mutable list with initialised value
val variable_name = mutableListOf(items)

This is the example of list usage.

fun main() {
    // create mutable list called items
    val items = mutableListOf("Java","Go")

    // add item into list
    items.add("PHP")
    items.add("NodeJS")

    // remove item from list
    items.remove("Java")

    // change item at index 1
    items[1] = "Kotlin"

    // prints out the items
    for (item in items) {
        println(item)
    }
}

Output

Go
Kotlin
NodeJS

Based on the code above, the mutable list is created then some items is added into list by using add() function. The item called Java is removed with remove() function that takes item as a parameter of the function. The item at index 1 is changed with [] operator. The items from list is prints out using for loop.

This is the list of basic operations that can be used in list. This operations is only available for mutable list.

Function Description
add(data) insert a data into the list
add(index, data) insert a data into the list in specific index
remove(data) remove a specific data inside list
removeAt(index) remove a data inside list in specific index
isEmpty() check if a list is empty
size get the size or length of the list

Set

Set is a data structure that only allows unique values or items. This is the basic syntax of creating set.

// with initialised value (read only)
val variable_name = setOf(items)

// create mutable set with empty value
val variable_name = mutableSetOf<data_type>()

// create mutable set with initialised value
val variable_name = mutableSetOf(items)

This is the example of set usage.

fun main() {
    // create empty set
    val items = mutableSetOf<Int>()

    // add some items
    items.add(11)
    items.add(24)
    items.add(31)

    // add same item (will be ignored)
    items.add(31)

    // prints out the size of set
    println("Set size: ${items.size}")

    // iterate through set with for loop
    for (item in items) {
        println(item)
    }

}

Output

Set size: 3
11
24
31

Based on the code above, the empty mutable set is created then some items is added using add() function. Because set only allows unique values, the same value (in this case 31) that will be inserted into set is ignored so the length of the size is equals 3.

This is the list of basic operations that can be used in set. This operations is only available for mutable set.

Function Description
add(data) insert a data into the set
remove(data) remove a specific data inside set
isEmpty() check if a set is empty
size get the size or length of the set

Map

Map is a data structure that allows key value pairs or items to be stored. This data structure is suitable to store key value pairs.

Map data structure is illustrated in this picture below.

This is the basic syntax of creating map.

// with initialised value (read only)
val variable_name = mapOf(pairs)

// create mutable map with empty value
val variable_name = mutableMapOf<key_type,value_type>()

// create mutable map with initialised value
val variable_name = mutableMapOf<key_type,value_type>(pairs)

This is the example of map usage.

fun main() {
    // create map to store course data
    val courses = mutableMapOf<String, String>()

    // add some courses
    courses["C001"] = "Java Basics"
    courses["C002"] = "Kotlin Basics"
    courses["C003"] = "MySQL Basics"

    // prints out the course using forEach
    courses.forEach { (key, course) ->
        println("$key: $course")
    }
}

Output

C001: Java Basics
C002: Kotlin Basics
C003: MySQL Basics

Based on the code above, the map is used to store some courses. The course item is added using [] (square brackets) to define the key then assign the value. The forEach is used to prints out the item from courses using lambda or anonymous function with key and course as the parameter.

This is the list of basic operations that can be used in map. This operations is only available for mutable map.

Function Description
replace(key, value) replace the value for specific key
remove(key) remove a data with specific key inside map
isEmpty() check if a map is empty
size get the size or length of the map

Functions for Collections

There are many functions that can be used for collections data type.

forEach

The forEach function can be used to iterate through collections. The forEach is a void function.

This is the example of forEach usage.

fun main() {
    // create list of integers
    val items = mutableListOf(1,2,3,4,5)

    // using forEach to iterate through list
    items.forEach { i -> println(i) }
}

Output

1
2
3
4
5

filter

The filter function is used to select certain items based on the specific criteria or condition.

This is the example of filter usage.

fun main() {
    // create a map to store course data
    val courses = mutableMapOf<String, String>(
        "C001" to "Java Basics",
        "C002" to "Java Advance",
        "C003" to "MySQL Basics"
    )

    // filter only basics courses
    val filtered = courses.filter { course -> course.value.contains("Basics") }

    // prints out the basics courses
    println("Filtered courses")
    filtered.forEach { (k, v) -> println("$k: $v") }
}

Output

Filtered courses
C001: Java Basics
C003: MySQL Basics

map

The map function is used to execute certain code for all items inside collection. This function is returns new collection so the original collection is not changed.

This is the example of map usage.

fun main() {
    // create a list of words
    val words = listOf("This","Is","The","Text","SAMPLE")

    // convert all words into lowercase words
    val updated = words.map { s -> s.toLowerCase() }

    // prints out the result
    updated.forEach { word -> println(word) }
}

Output

this
is
the
text
sample

sum

The sum function is used to perform sum calculation. This function is suitable only for collections that store numeric values.

fun main() {
    // create list of integers
    val scores = listOf(45,67,12,44,90)

    // calculate the sum
    val result = scores.sum()

    // prints out the sum value
    println("Result: $result")
}

Output

Result: 258

average

The average function is used to perform average calculation. This function is suitable only for collections that store numeric values.

fun main() {
    // create list of integers
    val scores = listOf(45,67,12,44,90)

    // calculate the average
    val result = scores.average()

    // prints out the average value
    println("Result: $result")
}

Output

Result: 51.6

String

String is a data type that can be used to store many alphanumeric characters. This is the basic syntax to create new String.

val variable_name = "value"

This is the example of String usage.

fun main() {
    // create some String data
    val username = "fastcoder"
    val password = "idontknow"

    println("using uppercase: ${username.toUpperCase()}")

    // create simple validation
    val isValid = username.length >= 6 && password.length >= 7

    if (isValid) {
        println("Register succeed!")
        // create simple code
        val code = username.substring(0,3)
        println("Your verification code: $code")
    } else {
        println("Your username or password is invalid!")
    }
}

Output

using uppercase: FASTCODER
Register succeed!
Your verification code: fas

Based on the code above, some function for String is used. The toUpperCase() is used to convert all characters into uppercase characters. The length is used to get the length of the String data. The substring() function is used to select certain characters in username.

This is the list of basic functions that can be used for String data type.

Function Description
toUpperCase() convert all the characters into uppercase
toLowerCase() convert all the characters into lowercase
contains(str) check if a given character or String (str) is exists inside String
length get the length of the String
isEmpty() check if a String is empty
substring(begin) get the string value from beginning index
substring(begin, end) get the string value from beginning index until the end index
plus(str) concatenate the String with the given String (str)
equals(str) check if a given String (str) is equals with the compared String
split(delimiters) split String into a list of characters or String

The substring(begin, end) mechanism is illustrated in this picture below.

Sources

  • Learn more about array in this link.

  • Learn more about collections data type in this link.

I hope this article is helpful for learning the Kotlin programming language. If you have any thoughts or comments you can write in the discussion section below.

22