The filterIndexed() extension function for sets in Kotlin returns a list containing only elements of the set that match the given predicate, with the predicate having access to the index of each element.
The syntax of Set.filterIndexed() extension function is:
fun <T> Set<T>.filterIndexed(predicate: (index: Int, T) -> Boolean): List<T>
This filterIndexed() extension function of Set returns a list containing only elements matching the given predicate.
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes the index and an element of the set and returns a Boolean indicating whether the element matches the condition. |
Set.filterIndexed() returns value of type List
.
In Kotlin, we can use the filterIndexed()
function to get a list of elements from a set of integers that are at even indices.
For example,
filterIndexed()
function with a predicate that checks if the index is even.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5, 6)
val evenIndexElements = numbers.filterIndexed { index, _ -> index % 2 == 0 }
println("Elements at even indices: $evenIndexElements")
}
Elements at even indices: [1, 3, 5]
In Kotlin, we can use the filterIndexed()
function to get a list of strings from a set that are at odd indices.
For example,
filterIndexed()
function with a predicate that checks if the index is odd.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry", "date")
val oddIndexFruits = fruits.filterIndexed { index, _ -> index % 2 != 0 }
println("Fruits at odd indices: $oddIndexFruits")
}
Fruits at odd indices: [banana, date]
In Kotlin, we can use the filterIndexed()
function on an empty set, which will return an empty list regardless of the predicate.
For example,
filterIndexed()
function with a predicate that checks if the index is even.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val filteredElements = emptySet.filterIndexed { index, _ -> index % 2 == 0 }
println("Filtered elements in empty set: $filteredElements")
}
Filtered elements in empty set: []
In this Kotlin tutorial, we learned about filterIndexed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.