Kotlin Array.filterIndexedTo() function
In Kotlin, the Array.filterIndexedTo()
function is used to filter elements of an array based on a given predicate, along with their indices, and then add the filtered elements to the destination collection.
This function is similar to Array.filterIndexed(), but it allows you to specify a destination collection to which the filtered elements will be added.
In this tutorial, we’ll explore the syntax of the Array.filterIndexedTo()
function and provide examples of its usage with a Kotlin Array.
Syntax
The syntax of the Array.filterIndexedTo()
function is as follows:
inline fun <T, C : MutableCollection<in T>> Array<out T>.filterIndexedTo(
destination: C,
predicate: (index: Int, T) -> Boolean
): C
where
Parameter | Description |
---|---|
destination | The destination collection to which the filtered elements will be added. |
predicate | A lambda function that takes an index and the corresponding element from the array and returns true or false based on the condition to be satisfied. |
Examples for Array.filterIndexedTo() function
1. Filtering Elements at Odd Indices to a List
In this example, we’ll use filterIndexedTo()
to filter elements at odd indices from an array of integers and add them to a list.
Kotlin Program
fun main() {
val numbersArray = arrayOf(10, 20, 30, 40, 50, 60, 70, 80, 90)
val oddIndexedNumbersList = mutableListOf<Int>()
// Filtering elements at odd indices to a list
numbersArray.filterIndexedTo(oddIndexedNumbersList) { index, _ -> index % 2 != 0 }
// Printing the original array and the result list
println("Given Array\n${numbersArray.joinToString(", ")}\n")
println("Odd Indexed Numbers List\n${oddIndexedNumbersList.joinToString(", ")}")
}
Output
Given Array
10, 20, 30, 40, 50, 60, 70, 80, 90
Odd Indexed Numbers List
20, 40, 60, 80
2. Filtering Elements to a Set
In this example, we’ll use filterIndexedTo()
to filter elements from an array of strings based on their indices and add them to a set.
Kotlin Program
fun main() {
val wordsArray = arrayOf("apple", "banana", "orange", "kiwi", "grape")
val filteredWordsSet = mutableSetOf<String>()
// Filtering elements to a set based on indices
wordsArray.filterIndexedTo(filteredWordsSet) { index, _ -> index % 2 == 0 }
// Printing the original array and the result set
println("Given Array\n${wordsArray.joinToString(", ")}\n")
println("Filtered Words Set\n${filteredWordsSet.joinToString(", ")}")
}
Output
Given Array
apple, banana, orange, kiwi, grape
Filtered Words Set
apple, orange, grape
Summary
In this tutorial, we’ve covered the Array.filterIndexedTo()
function in Kotlin arrays, its syntax, and how to use it to filter elements based on both their values and indices while adding the results to a specified collection.