Kotlin List – Access Index while Filtering

To access index of the elements while filtering elements in a Kotlin List, use filterIndexed() function. For each element in the List, the predicate lambda function receives index and element as parameters.

In this tutorial, we will learn how to use filterIndexed() function on a List, to filter its elements based on a condition/predicate with access to both index and element in the predicate.

The syntax to call filterIndexed() function on a List with a predicate is

List.filterIndexed(predicate)

predicate is a lambda function that takes the index and element of the List as parameter and returns a boolean value.

Return Value

List.filterIndexed() function returns a List.

Elements of the List that return true for the given predicate, make it to the filtered List.

The original list on which filterIndexed() function is called, remains unchanged. Therefore, we can fall filterIndexed() function on a List, or a Mutable List.

Examples

In the following program, we will take a List of Integers and filter the numbers based on the condition formed using index and the element.

Main.kt

fun main(args: Array<String>) {
    var myList = listOf(1, 4, 8, 5, 6, 9, 12, 10, 33)
    var filteredList = myList.filterIndexed({ index, x -> index > 1 && x % 2 == 0 })
    println("Original List : ${myList}")
    println("Filtered List : ${filteredList}")
}

Here, the lambda function: { index, x -> index > 1 && x % 2 == 0 } is the predicate to the filterIndexed() function.

For each element x in the List, only those elements that satisfy the condition index > 1 && x % 2 == 0 are returned in the resulting List.

Output

Original List : [1, 4, 8, 5, 6, 9, 12, 10, 33]
Filtered List : [8, 6, 12, 10]

In the following example, we will take a list of Strings, and filter only those strings whose index is exactly divisible by 2.

Main.kt

fun main(args: Array<String>) {
    var myList = listOf("This", "is", "a", "test", "list")
    var filteredList = myList.filterIndexed { index, x -> index % 2 == 0 }
    println("Original List : ${myList}")
    println("Filtered List : ${filteredList}")
}

Output

Original List : [This, is, a, test, list]
Filtered List : [This, a, list]
ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned how to filter a List using a condition/predicate with access to index in the predicate, using filterIndexed() function, with the help of examples.