Kotlin List indexOfFirst()
Syntax & Examples


Syntax of List.indexOfFirst()

There are 2 variations for the syntax of List.indexOfFirst() extension function. They are:

1.
fun <T> List<T>.indexOfFirst(predicate: (T) -> Boolean): Int

This extension function returns index of the first element matching the given predicate, or -1 if the list does not contain such element.

2.
fun <T> Iterable<T>.indexOfFirst( predicate: (T) -> Boolean ): Int

This extension function returns index of the first element matching the given predicate, or -1 if the collection does not contain such element.



✐ Examples

1 Example

In this example,

  • We create a list named list containing strings representing various fruits.
  • We use the indexOfFirst function to find the index of the first element in the list that starts with the letter 'c'.
  • The result is stored in result.
  • Finally, we print the value of result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry", "orange", "grape");
    val result = list.indexOfFirst { it.startsWith("c") }
    println(result);
}

Output

2

2 Example

In this example,

  • We create a list named list containing integers.
  • We use the indexOfFirst function to find the index of the first even number in the list.
  • The result is stored in result.
  • Finally, we print the value of result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(10, 20, 30, 40, 50)
    val result = list.indexOfFirst { it % 2 == 0 }
    println(result);
}

Output

0

3 Example

In this example,

  • We create a list named list containing strings representing various fruits.
  • We use the indexOfFirst function to find the index of the first element in the list that contains the letter 'z'.
  • Since none of the elements contain 'z', the result is -1.
  • Finally, we print the value of result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry", "orange", "grape")
    val result = list.indexOfFirst { it.contains("z") }
    println(result);
}

Output

-1

Summary

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