Kotlin – Filter list based on index

Kotlin – Filter values in list based on the index

To filter values in list based on their index in Kotlin, you can use List.filterIndexed() function.

The following is a step by step process to filter strings in a list based on the index.

  1. Consider that we are given a list of values in myList.
  2. Call filterIndexed() function on myList. Inside the function, you have access to the index and value. Now, you can form a predicate(condition) based on the index.
  3. The filterIndexed() function returns a new list with the values whose index satisfy the specified predicate(condition).

Example 1: Filter values whose index is even in the List

In this example, we take a list of values in myList, and filter the values that are at even numbered indices.

Program

fun main() {
    val myList = listOf(100, 200, 300, 400, 500, 600)

    val result = myList.filterIndexed{ index, value -> index % 2 == 0 }

    println(result)
}

Output

[100, 300, 500]

Example 2: Filter values in List whose index > 2

In this example, we take a list of values in myList, and filter the values whose index is greater than 2.

Program

fun main() {
    val myList = listOf(100, 200, 300, 400, 500, 600)

    val result = myList.filterIndexed{ index, value -> index > 2 }

    println(result)
}

Output

[400, 500, 600]