kotlin filterindexed
The filterIndexed
function in Kotlin is used to filter elements in a collection based on their index. It takes a predicate function as a parameter, which determines whether an element should be included in the resulting collection or not.
The filterIndexed
function follows these steps:
- It takes two parameters: the index and the element of the collection.
- It applies the predicate function to each element in the collection along with its index.
- If the predicate function returns
true
for a particular element, that element is included in the resulting collection. - If the predicate function returns
false
for a particular element, that element is excluded from the resulting collection. - The resulting collection contains only the elements for which the predicate function returned
true
.
Here is an example of how to use the filterIndexed
function in Kotlin:
val numbers = listOf(1, 2, 3, 4, 5, 6)
val filteredNumbers = numbers.filterIndexed { index, number -> index % 2 == 0 && number % 2 == 0 }
// filteredNumbers will contain [2, 4, 6]
In this example, the filterIndexed
function is used to filter out the even numbers at even indexes in the numbers
collection. The predicate function checks if the index is even (index % 2 == 0
) and if the number at that index is also even (number % 2 == 0
). The resulting collection, filteredNumbers
, will only contain the numbers that satisfy this condition.