The filterIndexedTo() extension function in Kotlin filters elements in a set based on a given predicate that takes both the index and the element as arguments, appending the matching elements to the specified destination collection.
The syntax of Set.filterIndexedTo() extension function is:
fun <T, C : MutableCollection<in T>> Set<T>.filterIndexedTo(destination: C, predicate: (index: Int, T) -> Boolean): C
This filterIndexedTo() extension function of Set appends all elements matching the given predicate to the given destination.
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The collection to which the filtered elements will be appended. |
predicate | required | A function that takes the index of an element and the element itself, returning true if the element should be included in the destination collection. |
Set.filterIndexedTo() returns value of type C
.
Using filterIndexedTo() to filter elements at even indices in a set and append them to a new list.
For example,
fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evenIndexed = mutableListOf<Int>()
numbers.filterIndexedTo(evenIndexed) { index, _ -> index % 2 == 0 }
println(evenIndexed)
}
[1, 3, 5, 7, 9]
Using filterIndexedTo() to filter elements in a set that are greater than their indices and append them to a new list.
For example,
fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val greaterThanIndex = mutableListOf<Int>()
numbers.filterIndexedTo(greaterThanIndex) { index, value -> value > index }
println(greaterThanIndex)
}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Using filterIndexedTo() to filter elements at odd indices in a set and append them to a new set.
For example,
fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val oddIndexedSet = mutableSetOf<Int>()
numbers.filterIndexedTo(oddIndexedSet) { index, _ -> index % 2 != 0 }
println(oddIndexedSet)
}
[2, 4, 6, 8, 10]
In this Kotlin tutorial, we learned about filterIndexedTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.