Kotlin Arrays : Creating, Iterating, Filtering and Explore ArrayList

Home » Kotlin » Kotlin Arrays : Creating, Iterating, Filtering and Explore ArrayList

Arrays are fundamental data structures in programming that allow us to store and manipulate collections of elements efficiently. We will dive into the world of Kotlin arrays, discovering what makes them special and exploring their different features.

Kotlin Arrays : Creating, Iterating, Filtering and Explore ArrayList

What is a Kotlin Array?

A Kotlin array is a fixed-size collection of elements of the same type. It provides a convenient way to group related data together and perform various operations on them. Unlike other programming languages, Kotlin arrays are objects, which means they offer a rich set of methods and properties for working with collections.

How to create Kotlin Arrays?

To create a Kotlin array, you can use either the arrayOf() or arrayOfNulls() functions. The arrayOf() function allows you to initialize an array with a specific set of elements, while the arrayOfNulls() function creates an array of a given size with all elements initialized to null.

Here’s an example of creating a Kotlin array using the arrayOf() function:

val points = arrayOf(10,20,30,40)

Main.kt

fun main()
{

    val points = arrayOf(10,20,30,40)
    for (point in points) println(point)

}

Output

10
20
30
40

How to access the third element of the above array?

   val third = points[2]
   println(third) // prints 30

Output

30

Accessing and Modifying Kotlin Array Elements

You can access individual elements of a Kotlin array using the index operator []. The index starts from zero for the first element and increments by one for each subsequent element.

 val points = arrayOf(10,20,30,40)
 // access the second element
 val secondElement = points[1]
 println("Second element $secondElement")
 // modifying 4th element
 points[3] = secondElement
 println("Forth Element ${points[3]}")

Second element 20
Forth Element 20

Null Safety : Using arrayOfNulls() Function

The arrayOfNulls() function to create a Kotlin array with a given size and initialize all elements to null.

fun main()
{
    val os = arrayOfNulls<String>(4)
    os[0] = "MacOS X"
    os[1] = "Linux"
    os[2] = "Android"

    for (name in os)
    {
        println(name)
    }
}

Output

MacOS X
Linux
Android
null

Kotlin Arrays Manipulation

Kotlin arrays have a fixed size, which means you cannot add or remove elements once the array is created. However, Kotlin provides extension functions to manipulate arrays efficiently.

To add elements to an array, you can use the plus() or plusElement() functions, which return a new array with the added elements. Similarly, to remove elements, you can use the filter() or filterNot() functions.

fun main()
{
    val points = arrayOf(4,7,71,8)
    points.forEach { point -> print(" $point |") }
    println()
    val newPoints = points.plus(5) // adds 5 to the array
    newPoints.forEach { point -> print(" |$point") }

}

Output

 4 | 7 | 71 | 8 |
 |4 |7 |71 |8 |5

How to apply plusElement() function in an Array?

fun main()
{
    val marks = arrayOf(56,93,98,44,15)
    val newMarks = marks.plusElement(59)
    newMarks.forEach { element -> println(element) }

}

[Learn more about Kotlin Lambda functions]

Output

56
93
98
44
15
59

Filter functions

To remove elements, you can use the filter() or filterNot() functions.


fun main()
{
    val items = arrayOf(6,8,20,0)
    val newItems  = items.plus(78)
    for (item in newItems) print(" $item")
    val filterItem = newItems.filter { it > 8 }
    println(filterItem)

}

Output

 6 8 20 0 78[20, 78]

Kotlin Multidimensional Arrays

In Kotlin, you can also create multidimensional arrays to represent matrices or grids. A multidimensional array is an array of arrays, where each inner array represents a row or column.

   val matrix = Array(3){
        IntArray(3) // 3x3 matrix
    }
    

Example.kt

Open the Kotlin Playground and write the following program.


fun main()
{
    val matrix = Array(3){
        IntArray(3) // 3x3 matrix
    }

    // Initializing the matrix elements
    matrix[0][0] = 1
    matrix[0][1] = 2
    matrix[0][2] = 3
    matrix[1][0] = 4
    matrix[1][1] = 5
    matrix[1][2] = 6
    matrix[2][0] = 7
    matrix[2][1] = 8
    matrix[2][2] = 9

    // Accessing and printing the matrix elements
    for (row in matrix) {
        for (element in row) {
            print("$element ")
        }
        println()
    }
}

Output

1 2 3 
4 5 6 
7 8 9 

In this example, we create a 3×3 matrix as a multidimensional array. The outer array, matrix, has a size of 3 and contains three inner arrays of size 3, which represent the rows of the matrix. We use the IntArray(3) statement to create each inner array.

Arrays vs Lists

Although Kotlin arrays provide efficiency and low memory overhead, there are cases where lists (ArrayList) might be more suitable. Unlike arrays, lists can dynamically grow or shrink in size and offer additional utility functions.

ArrayList Kotlin Example

fun main()
{
    val vegetables = ArrayList<String>()

    // Adding elements to ArrayList
    vegetables.add("Spinach")
    vegetables.add("Tomato")
    vegetables.add("Bitter Gourd")

    // accessing and printing the elements
    vegetables.forEach { element ->
        println(element)
    }
    
}

Output

Spinach
Tomato
Bitter Gourd

Let’s update an element at a specific index

    vegetables[1] = "Cabbage"
    // print using JoinToString()
    println(vegetables.joinToString())

Output

Spinach, Cabbage, Bitter Gourd

How to remove an element from ArrayList?

  // Removing an element 
    vegetables.remove("Spinach")
    println(vegetables.joinToString())

Output

Cabbage, Bitter Gourd

Checking if an element exists in the Kotlin ArrayList

   // Checking
    val containsCabbage = vegetables.contains("Cabbage")
    val result = if(containsCabbage) "Found" else "Not Found"
    println(result)

[Learn more about Kotlin Conditional Expression]

How to get the size of the ArrayList?

    val size = vegetables.size

ArrayList Example Program (Full)

Main.kt

package arrays

fun main()
{
    val vegetables = ArrayList<String>()

    // Adding elements to ArrayList
    vegetables.add("Spinach")
    vegetables.add("Tomato")
    vegetables.add("Bitter Gourd")

    // accessing and printing the elements
    vegetables.forEach { element ->
        println(element)
    }

    vegetables[1] = "Cabbage"
    // print using JoinToString()
    println(vegetables.joinToString())

    // Removing an element
    vegetables.remove("Spinach")
    println(vegetables.joinToString())

    // Checking
    val containsCabbage = vegetables.contains("Cabbage")
    val result = if(containsCabbage) "Found" else "Not Found"
    println(result)

    // Get the size of the ArrayList

    val size = vegetables.size
    println(size)


}

Arrays are powerful tools for organizing and manipulating collections of elements efficiently. Whether you need to store a list of numbers or create a matrix, arrays provide a versatile solution. With their intuitive syntax and built-in functions, arrays make it easy to work with data collections, iterate over elements, and perform common operations.

You may also like...