What is filterIndexed() method in Kotlin?
Kotlin is a modern programming language known for its simple syntax and powerful features designed for Android app development and backend applications to manipulate collections efficiently.
The filterIndexed() method
The filterIndexed() method filters elements from a collection based on a certain condition while also accessing their indices. This method helps retain the elements at specific positions or perform operations on elements with specific indices.
Syntax
The syntax of the filterIndexed() function is given below:
val result = collection.filterIndexed { index, element -> // Condition }
collectionrepresents the source collection from which you want to filter elements.indexrepresents the index of the current element being evaluated.elementrepresents the current element being evaluated.
Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.
Code
Let's look at the code given below to implement the filterIndexed() method.
Suppose we have a list of numbers, and we want to filter out elements that are even and have an odd index.
fun main() {val numbers = listOf(10, 20, 30, 40, 50)val filteredNumbers = numbers.filterIndexed { index, value ->index % 2 == 0 || value > 30}println("Filtered numbers: $filteredNumbers")}
Code explanation
Line 1–2: Firstly, we define a list of numbers.
Line 4–6: Next, we apply the
filterIndexed()function on the list. The lambda function is applied to each element and its corresponding index, and it returnstrueif either the index is even or the value is greater than 30. All the elements that satisfy this condition are put in thefilteredNumberslist.Line 8: Lastly, we print the filtered numbers on the console.
Output
Upon execution, the code selectively filters elements from a list of numbers using the filterIndexed() method based on the given conditions involving their values and indices.
The output of the code looks like this:
Filtered numbers: [10, 30, 40, 50]
Conclusion
Therefore, the filterIndexed() method in Kotlin serves as a valuable tool for filtering elements from collections based on specific conditions while using the indices of those elements. It can simplify code and control filtering for the developers so they can employ this method in their applications. This function offers a convenient way to enhance the efficiency of the code.
Free Resources