DEV Community

amay077
amay077

Posted on

Gets first index of match to condition in List

Extension method

inline fun <T> Iterable<T>.firstIndexOrNull(predicate: (T) -> Boolean): Int? {
    return this.mapIndexed { index, item -> Pair(index, item) }
            .firstOrNull() { predicate(it.second) }
            ?.first
}
Enter fullscreen mode Exit fullscreen mode

Just using .mapIndexed and .firstOrNull .

Usage

val arr = arrayListOf("a", "b", "c")

arr.firstIndexOrNull { it == "b"} // -> 1
arr.firstIndexOrNull { it == "z"} // -> null
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
egor profile image
Egor Neliuba

There's no need to manually go over the list using mapIndexed. Instead, you should use the built-in indexOfFirst extension function.