Kotlin List filterIndexed()
Syntax & Examples
Syntax of List.filterIndexed()
The syntax of List.filterIndexed() extension function is:
fun <T> Iterable<T>.filterIndexed( predicate: (index: Int, T) -> Boolean ): List<T>
This filterIndexed() extension function of List returns a list containing only elements matching the given predicate.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the integers1, 2, 3, 4, 5
. - We use the
filterIndexed
function onlist1
with a predicate that filters elements based on their index. - The predicate
{ index, value -> index % 2 == 0 }
keeps elements where the index is even. - The filtered list, containing elements at even indices, is stored in
result
. - Finally, we print the value of
result
to standard output using the print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5);
val result = list1.filterIndexed { index, value -> index % 2 == 0 }
print(result);
}
Output
[1, 3, 5]
2 Example
In this example,
- We create a list named
list2
containing the characters'a', 'b', 'c', 'd', 'e'
. - We use the
filterIndexed
function onlist2
with a predicate that filters elements based on their index. - The predicate
{ index, value -> index % 2 != 0 }
keeps elements where the index is odd. - The filtered list, containing elements at odd indices, is stored in
result
. - Finally, we print the value of
result
to standard output using the print statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf('a', 'b', 'c', 'd', 'e');
val result = list2.filterIndexed { index, value -> index % 2 != 0 }
print(result);
}
Output
[b, d]
3 Example
In this example,
- We create a list named
list3
containing the strings"apple", "banana", "cherry", "date", "elderberry"
. - We use the
filterIndexed
function onlist3
with a predicate that filters elements based on their index. - The predicate
{ index, value -> index > 1 }
keeps elements where the index is greater than 1 (i.e., skips the first two elements). - The filtered list, containing elements starting from index 2, is stored in
result
. - Finally, we print the value of
result
to standard output using the print statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "cherry", "date", "elderberry");
val result = list3.filterIndexed { index, value -> index > 1 }
print(result);
}
Output
[cherry, date, elderberry]
Summary
In this Kotlin tutorial, we learned about filterIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.