Kotlin List filterIndexedTo()
Syntax & Examples


Syntax of List.filterIndexedTo()

The syntax of List.filterIndexedTo() extension function is:

fun <T, C : MutableCollection<in T>> Iterable<T>.filterIndexedTo( destination: C, predicate: (index: Int, T) -> Boolean ): C

This filterIndexedTo() extension function of List appends all elements matching the given predicate to the given destination.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the integers 1, 2, 3, 4, 5.
  • We create a mutable destination list for integers named destination.
  • We use the filterIndexedTo function on list1 with a predicate that filters elements based on their index and appends them to destination.
  • The predicate { index, value -> index % 2 == 0 } keeps elements where the index is even.
  • Finally, we print the value of destination to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3, 4, 5);
    val destination = mutableListOf<Int>()
    list1.filterIndexedTo(destination) { index, value -> index % 2 == 0 }
    print(destination);
}

Output

[1, 3, 5]

2 Example

In this example,

  • We create a list named list2 containing the characters 'a', 'b', 'c', 'd', 'e'.
  • We create a mutable destination list for characters named destination.
  • We use the filterIndexedTo function on list2 with a predicate that filters elements based on their index and appends them to destination.
  • The predicate { index, value -> index % 2 != 0 } keeps elements where the index is odd.
  • Finally, we print the value of destination to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf('a', 'b', 'c', 'd', 'e');
    val destination = mutableListOf<Char>()
    list2.filterIndexedTo(destination) { index, value -> index % 2 != 0 }
    print(destination);
}

Output

[b, d]

3 Example

In this example,

  • We create a list named list3 containing the strings "apple", "banana", "cherry", "date", "elderberry".
  • We create a mutable destination list for strings named destination.
  • We use the filterIndexedTo function on list3 with a predicate that filters elements based on their index and appends them to destination.
  • The predicate { index, value -> index > 1 } keeps elements starting from index 2.
  • Finally, we print the value of destination to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf("apple", "banana", "cherry", "date", "elderberry");
    val destination = mutableListOf<String>()
    list3.filterIndexedTo(destination) { index, value -> index > 1 }
    print(destination);
}

Output

[cherry, date, elderberry]

Summary

In this Kotlin tutorial, we learned about filterIndexedTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.