Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

indexoffirst
arraylist
kotlin
communitycreator

How to use the indexOfFirst() method of ArrayList in Kotlin

Programming Bytes

Overview

The indexOfFirst() method will return the index of the first element of the ArrayList that satisfies the provided predicate functionPredicate is a Functional interface, which takes one argument and returns either true or false based on the condition defined. If no element matches the provided predicate function, then -1 is returned.

Syntax

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

Parameter

This method takes a predicate function as an argument.

Return value

This method returns an integer value denoting the index of the first element from the list that satisfies the provided predicate.

If no element matches, then -1 is returned.

Code

The method below demonstrates how to use the indexOfFirst() method.

fun main() {

  var list = ArrayList<Int>()
  list.add(1)
  list.add(2)
  list.add(3)
  println("The ArrayList is $list")

  var firstIndex = list.indexOfFirst({it % 2 == 0 })
  println("\nThe first index of even element is $firstIndex")

  firstIndex = list.indexOfFirst({it > 4})
  println("\nThe first index of elemen > 4 is $firstIndex")
}
Using the firstIndexOf method

Explanation

In the above code, we see the following:

  • Lines 3-6: We create a new ArrayList with the name list and add three elements to the list using the add() method. The list is [1,2,3].

  • Line 9: We use the indexOfFirst() method with a predicate function as an argument. This function will return true if the element is even. The indexOfFirst() method will loop through all elements of the ArrayList.

    • On index 0, the element present is 1, which is not even, so the predicate function returns false.
    • On index 1, the element present is 2, which is even, so the predicate function returns true. Due to this, the index of element 2 will be returned as a result of the indexOfFirst() method.
  • Line 12: We use the indexOfFirst() method with a predicate function as an argument. This function will return true if the element is greater than 4. In our ArrayList, there is no element that is greater than 4, so -1will be returned.

RELATED TAGS

indexoffirst
arraylist
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring