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.
filterIndexed()
methodThe 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.
The syntax of the filterIndexed()
function is given below:
val result = collection.filterIndexed { index, element -> // Condition }
collection
represents the source collection from which you want to filter elements.
index
represents the index of the current element being evaluated.
element
represents the current element being evaluated.
Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.
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")}
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 returns true
if either the index is even or the value is greater than 30. All the elements that satisfy this condition are put in the filteredNumbers
list.
Line 8: Lastly, we print the filtered numbers on the console.
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]
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