April 23, 2024

Stock Bitcoin

Bitcoin News and something more!

Arrays in Kotlin – Most used Methods

arrays kotlin

What is an array in Kotlin? Arrays are a data structure that consists of a collection of objects that allow sequential access through an index. They have been widely used since their appearance in high-level languages ​​(such as Python and Javascript) and have thus facilitated the handling of pointers (or pointers) in this language.

In Kotlin, we have several types of arrangements and lists, for example Array, ArrayList, List, MutableList, HashMap, etc. of which according to the use we want to give them, they have different uses.

However, because explaining the uses of different data structures, as well as their main methods is a broad topic, different tutorials will be made for each case. In this tutorial we will only focus on explaining the use of fixed Arrays in Kotlin and its main methods.

Arrays in Kotlin and their methods

It is an object with a fixed amount of values, that is, its fixed values ​​are declared from the beginning and they are accessed through an index. Let’s look at a very simple example:

val colors = arrayOf("Red", "Blue", "Green", "Yellow")

To access the values ​​of an array is very simple through an index. For example, to print the element of position 2, we write:

println(colors[2])

Where the color “Green” is shown, considering that the first index of the array is 0. We can also initialize array with a specific type, for example Int, which contains its own methods. The declaration is made through an intArray as shown below:

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

And some of intArray’s own methods and with their respective use example would be the following:

The average of the sum of elements

val average = numbers.average()
println("The average is $average")

Total elements, also applicable for other types of Arrays

val totalElements = numbers.count ()
println("In total $totalElements elements")

The sum of all intArray elements

val sumArray = numbers.sum ()
println("The sum of the array values ​​is $sumArray")

Get maximum and minimum array value

val maxValue = numbers.max ()
val minValue = numbers.min ()
println ("The highest value is $maxValue and the smallest is $minValue")

We can also apply a “for in”, to iterate over the list; in this way we can tour the elements with sequential access to them.

for (currentNumber in numbers) {
     print ("$currentNumber")
}

Array Ordering: A new array is generated with the numbers ordered, either ascending or descending.

val numbers = arrayOf(8, 3, 6, 9, 5)
val numbersOrderedAsc = numbers.sortedArray()
val numbersOrderedDesc = numbers.sortedArrayDescending()