Hello friends, In our previous article we discussed Array. Like what an array is and how it is defined in Kotlin with basic code examples. This tutorial is the second part of the previous article. In today’s tutorial, we will be discussing Array inbuild functions. Many array functions are available in Kotlin, and each has its own work. So let’s get started.
Master Kotlin Array Functions: A Complete Guide to Inbuilt Functions in Kotlin
- get(): The get method in the array is used to retrieve the given index element.
12345678val numbers = arrayOf(10, 20, 30, 40, 50)// Using the get() function to access elementsval firstElement = numbers.get(0) // retrieves the element at index 0// Printing the valuesprintln("First element: $firstElement") // Output: First element: 10 - iterator(): The iterator function provides an integrator that allows us to traverse through array elements using a loop.
1234567891011121314151617val languages = arrayOf("Kotlin", "Java", "Python", "C++")// Getting an iterator for the arrayval iterator = languages.iterator()// Using the iterator to loop through the arraywhile (iterator.hasNext()) {val language = iterator.next()println(language)}// OutputKotlinJavaPythonC++ - set(): The set function modifies a specific array element present on a specific index.
12345678// Creating an array of integersval numbers = arrayOf(1, 2, 3, 4, 5)// Modifying the element at index 2 using the set() functionnumbers.set(2, 10) // sets the value at index 2 to 10// Printing the modified arrayprintln(numbers.joinToString()) // Output: 1, 2, 10, 4, 5 - indices: The indices return us a valid index of array in Kotlin. It is useful when we get array values through the loop.
1234567891011121314// Creating an array of stringsval fruits = arrayOf("Apple", "Banana", "Cherry", "Date")// Using the indices property to loop through the array by indexfor (index in fruits.indices) {println("Element at index $index is ${fruits[index]}")}// OutputElement at index 0 is AppleElement at index 1 is BananaElement at index 2 is CherryElement at index 3 is Date - lastIndex: It returns us the last array element.
12345678// Creating an array of stringsval colors = arrayOf("Red", "Green", "Blue", "Yellow")// Using the lastIndex property to get the index of the last elementval lastIndex = colors.lastIndex// Accessing and printing the last element using lastIndexprintln("The last element is ${colors[lastIndex]}") // Output: The last element is Yellow - all{Condition}: All function checks the complete array with a given predicate(condition) and if the array satisfies the condition then it returns True and if not then returns false.
12345678// Creating an array of integersval numbers = arrayOf(2, 4, 6, 8, 10)// Using the all() function to check if all numbers are evenval allEven = numbers.all { it % 2 == 0 }// Printing the resultprintln("Are all numbers even? $allEven") // Output: Are all numbers even? true - any{condtion}: Any function returns true even if a single element of the array satisfies the given condition and only returns false when all the array elements do not satisfy the condition.
12345678// Creating an array of integersval numbers = arrayOf(1, 3, 5, 7, 10)// Using the any() function to check if any number is evenval anyEven = numbers.any { it % 2 == 0 }// Printing the resultprintln("Is there any even number? $anyEven") // Output: Is there any even number? true - asIterable(): This method converts the array into Iterable. This will be helpful when we want Iterable in for loop.
123456789101112131415161718// Creating an array of stringsval fruits = arrayOf("Apple", "Banana", "Cherry", "Date")// Converting the array to an Iterable using asIterable()val iterableFruits = fruits.asIterable()// Using a for loop to iterate over the Iterablefor (fruit in iterableFruits) {println(fruit)}// OutputAppleBananaCherryDate - asSequence(): This method converts the array into a Sequence. A Sequence is a lazy collection in easy words it only operates on its element on demand. Which led to high performance.
12345678910111213// Creating an array of integersval numbers = arrayOf(1, 2, 3, 4, 5)// Converting the array to a Sequence using asSequence()val numberSequence = numbers.asSequence()// Using map and filter operations on the sequenceval processedNumbers = numberSequence.map { it * it } // Square each number.filter { it > 5 } // Keep only numbers greater than 5// Printing the processed numbersprintln(processedNumbers.toList()) // Output: [9, 16, 25] - associate(): The associate method converts the array into a Map by a Key generated by a specific function.
123456789// Creating an array of fruitsval fruits = arrayOf("Apple", "Banana", "Cherry", "Date")// Using associate() to create a Map where the fruit names are the keys// and their lengths are the valuesval fruitMap = fruits.associate { fruit -> fruit to fruit.length }// Printing the resulting Mapprintln(fruitMap) // Output: {Apple=5, Banana=6, Cherry=6, Date=4} - associateBy(): It allows us to convert an array into a Map by extracting a key from each element from the array. The difference between associate() and associateBy() is in the associate method you can define the keys and values explicitly. In associateBy() automatically extract a key from each element.
1234567// Creating an array of fruitsval fruits = arrayOf("Apple", "Banana", "Cherry", "Date")val fruitMap = fruits.associateBy { fruit -> fruit.first() } // Key is the first letter// Printing the resulting Mapprintln(fruitMap) // Output: {A=Apple, B=Banana, C=Cherry, D=Date} - associateByTo(): The associateByTo() creates a Map from the array and stores it into a mutable map. The associateByTo() is almost similar to the associateBy() method but it gives us the option to store results into a target map.
1234567891011// Creating an array of fruitsval fruits = arrayOf("Apple", "Banana", "Cherry", "Date")// Creating a mutable map to hold the resultsval fruitMap = mutableMapOf<Char, String>()// Using associateByTo() to populate the mutable map with fruit names as valuesfruits.associateByTo(fruitMap) { fruit -> fruit.first() }// Printing the resulting Mapprintln(fruitMap) // Output: {A=Apple, B=Banana, C=Cherry, D=Date} - associateTo(): The associateTo() creates a Map from the given array and stores it into a map but it is different from associate() because the associate() creates a new map and associateTo() populates the given mutable map with key-value pairs.
1234567891011// Creating an array of fruitsval fruits = arrayOf("Apple", "Banana", "Cherry", "Date")// Creating a mutable map to hold the resultsval fruitMap = mutableMapOf<String, Int>()// Using associateTo() to populate the mutable map with fruit names as keys and their lengths as valuesfruits.associateTo(fruitMap) { fruit -> fruit to fruit.length }// Printing the resulting Mapprintln(fruitMap) // Output: {Apple=5, Banana=6, Cherry=6, Date=4} - associateWith(): The associateWith() also creates a Map from the collection but the values in the map are derived from a transformation function. It is used when we want to create a Map where Keys are the elements and values will be computed based on those elements.
123456789// Creating an array of fruitsval fruits = arrayOf("Apple", "Banana", "Cherry", "Date")// Using associateWith() to create a Map where the fruit names are the keys// and their lengths are the valuesval fruitMap = fruits.associateWith { fruit -> fruit.length }// Printing the resulting Mapprintln(fruitMap) // Output: {Apple=5, Banana=6, Cherry=6, Date=4} - associateWithTo(): This method in functionality similar to associateWith() but in associateWithTo() you can specify a target mutable map where the result will be stored.
123456789101112// Creating an array of fruitsval fruits = arrayOf("Apple", "Banana", "Cherry", "Date")// Creating a mutable map to hold the resultsval fruitMap = mutableMapOf<String, Int>()// Using associateWithTo() to populate the mutable map with fruit names as keys// and their lengths as valuesfruits.associateWithTo(fruitMap) { fruit -> fruit.length }// Printing the resulting Mapprintln(fruitMap) // Output: {Apple=5, Banana=6, Cherry=6, Date=4} - average(): The average function calculates the average value of the elements.
12345678// Creating an array of integersval numbers = arrayOf(1, 2, 3, 4, 5)// Calculating the average of the numbers in the arrayval average = numbers.average()// Printing the averageprintln("The average is: $average") // Output: The average is: 3.0 - binarySearch(): The binary search function is used to search a specific element in a sorted array and returns the index of the element. If in any case the element is not found then it returns a negative index position.
12345678910111213// Creating a sorted array of integersval numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)// Searching for an element in the arrayval target = 5val index = numbers.binarySearch(target)// Checking the resultif (index >= 0) {println("Element $target found at index $index.") // Output: Element 5 found at index 4.} else {println("Element $target not found.")} - contains(): The contains function in Kotlin is used to check if the array contains a specific element. It returns true if the element is found and if not found then returns false.
12345678910// Creating an array of integersval numbers = arrayOf(1, 2, 3, 4, 5)// Checking if the array contains the number 3val containsThree = numbers.contains(3)println("Does the array contain 3? $containsThree") // Output: Does the array contain 3? true// Checking if the array contains the number 6val containsSix = numbers.contains(6)println("Does the array contain 6? $containsSix") // Output: Does the array contain 6? false - contentEquals(): The content equals function compares the contents present in one array with another array and returns true if both have the same content with the same order and return false otherwise.
123456789101112// Creating two arrays of integersval array1 = arrayOf(1, 2, 3, 4, 5)val array2 = arrayOf(1, 2, 3, 4, 5)val array3 = arrayOf(5, 4, 3, 2, 1)// Using contentEquals() to compare arraysval areEqual1 = array1.contentEquals(array2)val areEqual2 = array1.contentEquals(array3)// Printing the resultsprintln("Are array1 and array2 equal? $areEqual1") // Output: Are array1 and array2 equal? trueprintln("Are array1 and array3 equal? $areEqual2") // Output: Are array1 and array3 equal? false - contentHashCode(): The content hash code function generates a hash code that considers the elements in the array.
1234567891011// Creating an array of integersval numbers = arrayOf(1, 2, 3, 4, 5)// Calculating the content hash code of the arrayval hashCode = numbers.contentHashCode()// Printing the hash codeprintln("Content hash code of numbers array: $hashCode")// OutputContent hash code of numbers array: 29615266 - contentToString(): The content to string function returns a string representation of the Array. This is used to show all array items at once in string formation.
1234567val numbers = arrayOf(1, 2, 3, 4, 5)// Printing the array directly (shows the memory reference)println(numbers) // Output: [Ljava.lang.Integer;@3b07d329// Using contentToString() to print array elements as stringprintln(numbers.contentToString()) // Output: [1, 2, 3, 4, 5] - count(): The count function in Kotlin array counts the total number of elements present in the array, like how many items our array has.
123456val numbers = arrayOf(1, 2, 3, 4, 5)// Counting the total number of elements in the arrayval totalCount = numbers.count()println("Total number of elements: $totalCount") // Output: 5 - distinct(): The distinct function in the Kotlin array returns unique elements present in the array.
123456val numbers = arrayOf(1, 2, 2, 3, 4, 4, 5)// Using distinct() to get unique elementsval distinctNumbers = numbers.distinct()println(distinctNumbers) // Output: [1, 2, 3, 4, 5] - distinctBy(): The distinct by function in Kotlin array filters unique elements from the array based on a specific key.
123456val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)// Using distinctBy() to get distinct elements by their remainder when divided by 3val distinctByRemainder = numbers.distinctBy { it % 3 }println(distinctByRemainder) // Output: [1, 2, 3] - drop(): The drop function in the Kotlin array has an N argument which represents as starting index. It returns us a new array removing N elements.
123456val numbers = arrayOf(1, 2, 3, 4, 5)// Dropping the first 2 elementsval result = numbers.drop(2)println(result) // Output: [3, 4, 5] - dropLast(): The drop last function is just the opposite of the drop. When in drop it removes starting items, In drop last it removes items from the last of the array.
123456val numbers = arrayOf(1, 2, 3, 4, 5)// Dropping the last 2 elementsval result = numbers.dropLast(2)println(result) // Output: [1, 2, 3] - dropLastWhile(): The drop last while function in the Kotlin array removes elements starting from the end in the array as per the given condition and returns us condition-satisfied elements.
123456val numbers = arrayOf(1, 2, 3, 4, 5, 6)// Dropping the last elements while they are greater than 3val result = numbers.dropLastWhile { it > 3 }println(result) // Output: [1, 2, 3] - dropWhile(): The drop while function only removes elements from the array based on the given condition from the start of the array.
123456val numbers = arrayOf(1, 2, 3, 4, 5, 6)// Dropping elements from the beginning while they are less than 4val result = numbers.dropWhile { it < 4 }println(result) // Output: [4, 5, 6] - elementAtOrElse(): The element at or else method retrieves an element from a specific index from the array. If the element is not found on that particular index then instead of throwing an error it handles the error and returns us our given fallback value defined by us.
123456val numbers = arrayOf(10, 20, 30, 40, 50)// Accessing the element at index 2val element = numbers.elementAtOrElse(2) { -1 }println(element) // Output: 30 - elementAtOrNull(): The element at or null function fetches us the element present on a specific index and if the item is not found or the index is out then it returns us NULL.
123456val numbers = arrayOf(10, 20, 30, 40, 50)// Accessing the element at index 2val element = numbers.elementAtOrNull(2)println(element) // Output: 30 - filter(): The filter function in Kotlin array filters the array elements based on a given condition.
12345678910111213val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)// Filtering even numbersval evenNumbers = numbers.filter { it % 2 == 0 }println(evenNumbers) // Output: [2, 4, 6, 8, 10]val fruits = arrayOf("Apple", "Banana", "Cherry", "Blueberry", "Avocado")// Filtering fruits that start with the letter 'A'val fruitsStartingWithA = fruits.filter { it.startsWith("A") }println(fruitsStartingWithA) // Output: [Apple, Avocado] - filterIndexed(): The Kotlin filter array’s filter index function is based on index and element values.
123456val numbers = arrayOf(10, 20, 30, 40, 50, 60)// Filtering elements that are at even indicesval evenIndexElements = numbers.filterIndexed { index, _ -> index % 2 == 0 }println(evenIndexElements) // Output: [10, 30, 50] - filterIndexedTo(): The filter indexed to the method in Kotlin array filter elements in an array based on both index and element value. In this method, we can apply a predicate function to each element of an array with its index and it will return us a collection that satisfies our predicate(condition).
1234567891011121314151617// Source arrayval numbers = arrayOf(10, 20, 30, 40, 50)// Destination mutable listval filteredList = mutableListOf<Int>()// Filter elements where the element is greater than 25 and the index is evennumbers.filterIndexedTo(filteredList) { index, value ->index % 2 == 0 && value > 25}// Print the resultprintln("Filtered List: $filteredList")// OutputFiltered List: [30, 50] - filterIsInstance(): The filterIsInstance function in the Kotlin array is used when we have different data type values in a single variety. It filters elements based on specific data types.
12345678910111213141516/ Mixed-type arrayval mixedArray: Array<Any> = arrayOf(1, "Hello", 2.5, "World", 42, 3.14)// Filter only the stringsval stringList: List<String> = mixedArray.filterIsInstance<String>()// Filter only the integersval intList: List<Int> = mixedArray.filterIsInstance<Int>()// Print the filtered listsprintln("Strings: $stringList")println("Integers: $intList")// OutputStrings: [Hello, World]Integers: [1, 42] - filterIsInstanceTo(): The filterIsInstanceTo method in Kotlin filters a specific type of data from an array and then adds it to the destination array.
123456789101112131415// Mixed type arrayval mixedArray = arrayOf(1, "Hello", 2.5, 3, "World", 4.5)// Destination list to store only integersval intList = mutableListOf<Int>()// Filter out integers from mixedArray and add them to intListmixedArray.filterIsInstanceTo(intList)// Print the resultprintln("Filtered Integers: $intList")// OutputFiltered Integers: [1, 3] - filterNot(): The filter not function of the array in Kotlin filters out the elements of an array based on the predicate. It returns us a list of all the elements which do not satisfy the given predicate.
12345678910// Source arrayval names = arrayOf("Alice", "Bob", "Charlie", "David")// Filter out names that start with 'A'val filteredNames = names.filterNot { it.startsWith("A") }// Print the resultprintln("Filtered Names: $filteredNames")Filtered Names: [Bob, Charlie, David] - filterNotNull(): The filter-null method in Kotlin array filters all the null values from a given array and returns us a List containing only nonnull values.
1234567891011// Source array with nullable elementsval arrayWithNulls = arrayOf(1, 2, null, 4, null, 6)// Filter out all null valuesval nonNullList = arrayWithNulls.filterNotNull()// Print the resultprintln("Non-null elements: $nonNullList")// OutputNon-null elements: [1, 2, 4, 6] - filterNotNullTo(): The filter not null to the method in Kotlin array filters out all the nonnull values from an array and we can store this to a destination location.
123456789101112131415// Source array with nullable elementsval arrayWithNulls = arrayOf(1, null, 3, null, 5)// Destination mutable listval nonNullList = mutableListOf<Int>()// Filter out the null elements and add the non-null ones to the destinationarrayWithNulls.filterNotNullTo(nonNullList)// Print the resultprintln("Non-null elements: $nonNullList")// OutputNon-null elements: [1, 3, 5] - filterNotTo(): The filterNotTo method in the Kotlin array filters out all the elements that do not satisfy the given predicate and transfers the remaining elements to a destination collection.
123456789101112131415// Source arrayval numbers = arrayOf(10, 20, 30, 40, 50)// Destination mutable listval filteredList = mutableListOf<Int>()// Filter out elements that are greater than 30numbers.filterNotTo(filteredList) { value ->value > 30}// Print the resultprintln("Filtered List: $filteredList")Filtered List: [10, 20, 30] - filterTo(): The filterTo method in the Kotlin array filters elements in a collection based on a specific predicate and stores results in the destination array. It returns us only those elements that satisfy the condition.
1234567891011121314// Source arrayval numbers = arrayOf(5, 10, 15, 20, 25, 30)// Destination mutable listval filteredList = mutableListOf<Int>()// Filter elements that are greater than 15numbers.filterTo(filteredList) { it > 15 }// Print the resultprintln("Filtered List: $filteredList")// OutputFiltered List: [20, 25, 30]