loading...

Gets first index of match to condition in List

twitter logo github logo ・1 min read

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
}

Just using .mapIndexed and .firstOrNull .

Usage

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

arr.firstIndexOrNull { it == "b"} // -> 1
arr.firstIndexOrNull { it == "z"} // -> null
twitter logo DISCUSS (1)
markdown guide
 

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

Classic DEV Post from May 25 '19

Yes, You Should Have Hobbies Outside of Code

Hobbies give us a break from the real world. Take all you can get.

amay077 profile image
Microsoft MVP(Xamarin). Android / iOS app developer. Love C#.

Hey there reader...

Do you prefer sans serif over serif?

You can change your font preferences in the "misc" section of your settings. ❤️