What is Array in kotlin?
Array is a collection of similar data types such as an Int, String etc. It is used to organize data so sorted and searched can be easily done.
Arrays are mutable and fixed size, they are stored in contiguous memory locations.
Create an Array
1. Using the arrayOf() function –
val x = arrayOf(1, 2, 3, 4) //implicit type declaration
val y = arrayOf<Int>(1, 2, 3) //explicit type declaration
val names = arrayOf<String>("Josh", "Sanjay", "justin")
Kotlin has some built-in factory methods to create an array of primitive data types such as :
arrayOf()
intArrayOf()
charArrayOf()
booleanArrayOf()
longArrayOf()
shortArrayOf()
byteArrayOf()
var arr1: IntArray = intArrayOf(1,2,3,4,5)
var arr2: BooleanArray = booleanArrayOf(true,false,true)
2. Using the Array constructor –
The constructor takes two parameter first size of array and second function which accepts the index of a given element and returns the initial value of that element.
Syntax :
Array(size: Int, init: (Int) -> T)
val num = Array(5, {i-> i*1})
Example :
fun main()
{
val arr = Array(3, { i -> i * 1 })
for (i in 0..arr.size-1)
{
println(arr[i])
}
}
Output
0
1
2
3. Using arrayOfNulls
:
It is used to create an array of a specified size where all elements are initialized to null
.
val nullArray: Array<Int?> = arrayOfNulls(arrSize)
fun main() {
val arrSize = 5
// Create an array of 5 nullable integers initialized to null
val nullArray: Array<Int?> = arrayOfNulls(arrSize)
nullArray[0] = 23 //assign value
for( i in 0..nullArray.size-1){
print(" ${nullArray[i]}")
}
}
/**
Output
23 null null null null
*/
4. Initialize an array of size with default value : –
we can initialize an array of size 3 with default value, example
fun main(args: Array<String>){
var myArray = Array<Int>(3){12}
for(x in myArray){
println(x)
}
}
Output
12
12
12
12
12
Kotlin provides several classes for arrays of different primitive types like IntArray, CharArray, DoubleArray, FloatArray, LongArray, ShortArray to initialize array with default value and size. If using IntArray and LongArray The elements are initialized with default values 0, for FloatArray and DoubleArray elements are initialized with default values is 0.0. Here are a few examples:
fun main() {
val intArray = IntArray(5)
intArray[0] = 1
// get default value 0 for 1st index
println(intArray[1]) // 0
val charArray = CharArray(5)
charArray[0] = 'A'
println(charArray[0]) // A
val doubleArray = DoubleArray(5)
println(doubleArray[0]) // 0.0
val floatArray = FloatArray(5)
println(floatArray[0]) // 0.0
val longArray = LongArray(5)
println(longArray[0]) // 0
}
Modify and access elements of an array : –
Kotlin provides a set() function to modify an array and access the element of the array. You can also modify an array by assigning elements at array index.
set() function example :
fun main(args: Array<String>) {
val arr1 = arrayOf(1,2,3,4)
val arr2 = arrayOf<Int>(100,101,102,103)
arr1.set(0,9)
arr1[1] = 90 //assigning element at array index
for(element in arr1){
println(element)
}
}
Output
9
90
3
4
get() function example :
fun main(args: Array<String>) {
val arr1 = arrayOf(1,2,3,4)
val arr2 = arrayOf<Int>(100,101,102,103)
println(arr1.get(3))
println(arr1[2]) // get element by index
// println(arr1[4]) // java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
}
Output
4
3
when we try get or set an element at index position greater than array size then it will throw an ArrayIndexOutOfBoundsException.
Traverse an array using the range function : –
Kotlin array elements are also traversed by index range function , range(minVal..maxVal) or range(maxVal..minVal).
fun main(args: Array<String>){
var arr = intArrayOf(2,4,6,8,10)
for (index in 0..arr.size-1){
println(arr[index])
}
}
Output
2
4
6
8
10
Array Functions & Property:
1. size
Property: Returns the size (number of elements) of the array.
val numbers = arrayOf(1, 2, 3, 4, 5)
val arraySize: Int = numbers.size
println("Array Size: $arraySize") // Array Size: 5
2. isEmpty()
Function: Returns true
if the array is empty otherwise, returns false
.
fun main() {
val emptyArray = emptyArray<Int>()
val isNotEmpty: Boolean = arrayOf(1,2,2).isNotEmpty()
val isEmpty: Boolean = emptyArray.isEmpty()
println("Is 'numbers' not empty: $isNotEmpty")//Is 'numbers' not empty: true
println("Is 'emptyArray' empty: $isEmpty")//Is 'emptyArray' empty: true
}
3. contains()
Function: Returns true
if the array contains the specified element; otherwise, returns false
.
val fruits = arrayOf("Mango", "Cherry", "Litchi")
val containsBanana: Boolean = fruits.contains("Mango") // returns true
val containsGrapes: Boolean = fruits.contains("banana") // returns false
4. indexOf()
Function: Returns the index of the first occurrence of the specified element in the array, or -1 if the element is not found.
val fruits = arrayOf("Mango", "Cherry", "Litchi")
val indexCherry: Int = fruits.indexOf("Litchi")// return 2
val indexGrapes: Int = fruits.indexOf("grapes")// return -1
5.indices
property : It is used to obtain a range of valid indices for an array . It returns a range from 0
to size - 1
val fruits = arrayOf("apple", "banana", "cherry")
// Using 'indices' to iterate over the indices of the array
for (index in fruits.indices) {
println("Index $index: ${fruits[index]}")
}
Output
Index 0: apple
Index 1: banana
Index 2: cherry
6. withIndex() Function : It returns an iterable of IndexedValue
objects, where each object contains the index and the corresponding element. Here’s an example using an array:
fun main() {
val fruits = arrayOf("Mango", "Cherry", "Litchi")
// Using 'withIndex' to iterate over elements and indices
for ((index, fruit) in fruits.withIndex()) {
println("Index $index: $fruit")
}
}
here is output:
Index 0: Mango
Index 1: Cherry
Index 2: Litchi
6. filter()
Function: Returns a new list containing only the elements matching the given predicate or condition.
val fruits = arrayOf("Mango", "Cherry", "Litchi")
val numbers = arrayOf(3,5,6,1,3,3)
val evenNumbers: List<Int> = numbers.filter { it % 2 == 0 }
val shortFruits: List<String> = fruits.filter { it.length < 6 }
println("Even numbers: $evenNumbers") // Even numbers: [6]
println("Short fruits: $shortFruits") // Short fruits: [Mango]
7. first()
, last()
: first()
return the first or last()
returns the last element of the array, or give exception
if the array is empty.
fun main() {
val numbers = arrayOf(12,4,5,6)
val fruits = arrayOf("Banana","Apple","Litchi")
val firstNumber: Int = numbers.first()
val lastFruit: String = fruits.last()
println("First number: $firstNumber")
println("Last fruit: $lastFruit")
}
Output
//Output
First number: 12
Last fruit: Litchi
8. firstOrNull()
and lastOrNull()
: It returns the first or last element of a collection, respectively, matching the given predicate or condition. If no element is found, they return null
.
val numbers = listOf(1, 2, 3, 4, 5, 6)
val firstEven: Int? = numbers.firstOrNull { it % 2 == 0 }
val firstGreaterThanTen: Int? = numbers.firstOrNull { it > 10 }
println("First even number: $firstEven") // Output: 2
println("First number greater than 10: $firstGreaterThanTen") // Output: null
Here’s a simple example of lastOrNull
:
fun main() {
val numbers = listOf(10, 20, 30, 40, 50, 60)
// Find the last element greater than 30
val lastGreaterThan30: Int? = numbers.lastOrNull { it > 30 }
// Find the last element that is less than 10 (which doesn't exist)
val lastLessThan10: Int? = numbers.lastOrNull { it < 10 }
println("Last element greater than 30: $lastGreaterThan30") // Output: 60
println("Last element less than 10: $lastLessThan10") // Output: null
}
//Output
Last element greater than 30: 60
Last element less than 10: null
9.toTypedArray() function : List
can be converted to an array using the toTypedArray()
function.
fun main() {
val myList = listOf("apple", "banana", "orange")
// Convert the list to an array
val myArray = myList.toTypedArray()
// Print the elements of the array
for (item in myArray) {
print("$item ")
}
}
/*
Output
apple banana orange
* */
Copy array elements using spread operator(*)
The spread operator can be used to copy the elements of an array into a new array.
fun main() {
val fruits = arrayOf("apple", "banana", "orange")
// Creating a new array using the spread operator
val newArray = arrayOf(*fruits, "grape", "kiwi")
println("New Array: ${newArray.joinToString(", ")}")
}
/**
Output
New Array: apple, banana, orange, grape, kiwi
* */
Here, the spread operator is used to combine the elements of an existing array (fruits
) with additional elements to create a new array (newArray
).