Ebooks

Kotlin arrays

Kotlin arrays tutorial shows how to work with arrays in Kotlin.

An array is a collection of a fixed number of values. The array items are called elements of the array. Each element can be referred to by an index. Arrays are zero based.

Kotlin arrays are created with functions such as arrayOf() or intArrayOf(), or with classes such as IntArray or FloatArray.

Kotlin array initialization

In the first example, we show how we can initialize arrays in Kotlin.

KotlinArrayInit.kt
package com.zetcode

import java.util.Arrays

fun main(args: Array<String>) {

    val nums = arrayOf(1, 2, 3, 4, 5)
    println(Arrays.toString(nums))

    val nums2 = (3..12).toList().toTypedArray()
    println(Arrays.toString(nums2))

    val nums3 = IntArray(5, { i -> i * 2 + 3})
    println(Arrays.toString(nums3))
}

The example creates three arrays.

val nums = arrayOf(1, 2, 3, 4, 5)

An array is created with arrayOf() function.

println(Arrays.toString(nums))

We use Arrays' toString() method to print the contents of the array.

val nums2 = (3..12).toList().toTypedArray()

In this line, we create an array from a range of numbers.

val nums3 = IntArray(5, { i -> i * 2 + 3})

This line creates an array with IntArray. It takes the number of elements and a factory function as parameters.

[1, 2, 3, 4, 5]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[3, 5, 7, 9, 11]

This is the output.

Kotlin array indexing

The next example shows the array indexing operations in Kotlin.

KotlinArrayIndexing.kt
package com.zetcode

fun main(args: Array<String>) {

    val nums = intArrayOf(1, 2, 3, 4, 5)

    println(nums[2])

    nums[0] = 11
    println(nums[0])
}

We use the indexing operations to get and modify an array value.

println(nums[2])

We print the value with index 2, i.e. the third element in the array. The index of an array value is added between a pair of square brackets.

Kotlin array basic operations

The following example presents some basic operations with Kotlin arrays.

KotlinArrayBasicOperations.kt
package com.zetcode

import java.util.Arrays

fun main(args: Array<String>) {

    val nums = arrayOf(1, 2, 3, 4, 5)
    println(nums.get(0))

    nums.set(0, 0)
    println(Arrays.toString(nums))

    val nums2 = nums.plus(1)
    println(Arrays.toString(nums2))

    val slice = nums.sliceArray(1..3)
    println(Arrays.toString(slice))

    println(nums.first())
    println(nums.last())
    println(nums.indexOf(5))
}

In the example, we retrieve and modify array elements, create a slice, and get an index of an element.

println(nums.get(0))

We get an element with index 0 using the get() function.

nums.set(0, 0)

The set() method sets the array element at the specified index to the specified value.

val nums2 = nums.plus(1)

We add a new element to the array, creating a new array. (Remember that arrays are fixed sized; therefore, a new array was created).

val slice = nums.sliceArray(1..3)

With the sliceArray() method, we create a slice from the array. The indexes are both inclusive.

println(nums.first())
println(nums.last())

We get the first and the last element of the array.

println(nums.indexOf(5))

We get the index of the first occurrence of the element 5.

1
[0, 2, 3, 4, 5]
[0, 2, 3, 4, 5, 1]
[2, 3, 4]
0
5
4

This is the output.

Kotlin array built-ins

In the following example, we use some built-in array methods.

KotlinArrayBuiltins.kt
package com.zetcode

fun main(args: Array<String>) {

    val nums = intArrayOf(1, 2, 3, 4, 5)

    val avg = nums.average()
    println("The average is $avg")

    val nOfValues = nums.count()
    println("There are $nOfValues elements")

    val sumOfValues = nums.sum()
    println("The sum of values is $sumOfValues")

    val maxValue = nums.max()
    println("The maximum is $maxValue")

    val minValue = nums.min()
    println("The minimum is $minValue")
}

The example computes the average, sum, maximum, minimum, and the size of an array.

val avg = nums.average()

The average() function calculates the average of the array values.

val nOfValues = nums.count()

The number of elements is determined with count().

The average is 3.0
There are 5 elements
The sum of values is 15
The maximum is 5
The minimum is 1

This is the output of the example.

Kotlin array traversal

In the next example, we loop over Kotlin arrays.

KotlinTraverseArrays.kt
package com.zetcode

fun main(args: Array<String>) {

    val nums = arrayOf(1, 2, 3, 4, 5, 6, 7)

    nums.forEach({ e -> print("$e ") })

    println()

    nums.forEachIndexed({i, e -> println("nums[$i] = $e")})

    for (e in nums) {
        print("$e ")
    }

    println()

    val it: Iterator<Int> = nums.iterator()

    while (it.hasNext()) {
        
        val e = it.next()
        print("$e ")
    }
}

The example loops over an array using four different ways of traversal.

nums.forEach({ e -> print("$e ") })

We traverse the array with forEach(). This method applies an action on each element of the array. It prints it in our case.

nums.forEachIndexed({i, e -> println("nums[$i] = $e")})

The forEachIndexed() performs the given action on each element, providing sequential index with the element.

for (e in nums) {
    print("$e ")
}

We go over the array in a for loop.

val it: Iterator<Int> = nums.iterator()

while (it.hasNext()) {
    
    val e = it.next()
    print("$e ")
}

Finally, we traverse the array with an iterator and a while loop.

1 2 3 4 5 6 7 
nums[0] = 1
nums[1] = 2
nums[2] = 3
nums[3] = 4
nums[4] = 5
nums[5] = 6
nums[6] = 7
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 

This is the output of the example.

Sorting arrays in Kotlin

We show how to sort Kotlin arrays.

KotlinArraySort.kt
package com.zetcode

fun main(args: Array<String>) {

    val nums = arrayOf(7, 3, 3, 4, 5, 9, 1)

    val sortedNums = nums.sortedArray()
    println(Arrays.toString(sortedNums))

    val sortedNumsDesc = nums.sortedArrayDescending()
    println(Arrays.toString(sortedNumsDesc))
}

The example sorts an array is ascending order with sortedArray() and descending order with sortedArrayDescending(). The methods create new sorted arrays.

[1, 3, 3, 4, 5, 7, 9]
[9, 7, 5, 4, 3, 3, 1]

This is the output of the example.

Kotlin two-dimensional arrays

In Kotlin, we can create two-dimensional arrays.

KotlinArrayTwoDim.kt
package com.zetcode

fun main(args: Array<String>) {

    val array = arrayOf(intArrayOf(1, 2),
            intArrayOf(3, 4),
            intArrayOf(5, 6, 7))

    println(Arrays.deepToString(array))
}

The example creates a two-dimensional array by nesting intArrayOf() function calls into the arrayOf() function.

[[1, 2], [3, 4], [5, 6, 7]]

This is the output.

Kotlin filtering arrays

With the filter() method, we can filter data in an array.

KotlinArrayFilter.kt
package com.zetcode

fun main(args: Array<String>) {

    val nums = arrayOf(1, -2, 3, 4, -5, 7)

    nums.filter { e -> e > 0 }.forEach { e -> print("$e ") }
}

The example creates an array of positive and negative integers. The filter() method is used to pick up only positive values.

1 3 4 7 

This is the output.

Kotlin array reduction

Reduction is a terminal operation that aggregates array values into a single value. The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

KotlinArrayReduce.kt
package com.zetcode

fun main(args: Array<String>) {
    
    val nums = intArrayOf(2, 3, 4, 5, 6, 7)

    val total = nums.reduce { product, next -> product * next }

    println(total)
}

We use the reduce() method to calculate a product from array elements.

val total = nums.reduce { product, next -> product * next }

The product is the accumulator, the next is the next value in the array.

5040

This is the output.

In this tutorial, we have covered Kotlin arrays. You might also be interested in the related tutorials: Kotlin Ranges tutorial, Kotlin lists tutorial, Kotlin variables tutorial, Kotlin strings tutorial, Kotlin control flow, Kotlin read file tutorial, and Kotlin write file tutorial.