Kotlin has array.indexOf(item)
but I cannot figure out how to do array.indexOfBy { lambda }
. Does it not exist? I can find
an item, but I cannot get its index at the same time.
Am I missing a function in the stdlib?
I can create a function with a loop that chekcs the items and returns when it finds the target. Like this:
fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
for (i in items.indices) { // or (i in 0..items.size-1)
if (predicate(items[i])) {
return i
}
}
return -1
}
Then I tried to make it a little more functional using forEach
:
fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
(items.indices).forEach {
if (predicate(items[it])) {
return it
}
}
return -1
}
Or I can do something silly like this which isn't very performant:
val slowAndSilly = people.indexOf(people.find { it.name == "David" })
And what looks best is maybe as extension functions:
fun <T: Any> Array<T>.indexOfBy(predicate: (T)->Boolean): Int =
this.withIndex().find { predicate(it.value) }?.index ?: -1
fun <T: Any> Collection<T>.indexOfBy(predicate: (T)->Boolean): Int =
this.withIndex().find { predicate(it.value) }?.index ?: -1
fun <T: Any> Sequence<T>.indexOfBy(predicate: (T)->Boolean): Int =
this.withIndex().find { predicate(it.value) }?.index ?: -1
Is there a more elegant and idiomatic way to accomplish this?!? I also don't see a function like this for lists, collections nor sequences.
(this question is derived from the comment on another post)
Using arrayOf() function In Kotlin, you can use the indexOf() function that returns the index of the first occurrence of the given element, or -1 if the array does not contain the element.
Kotlin List – Find Index of an Element. To find the index of a specific element in this List, call indexOf() function on this List, and pass the element as argument to this indexOf() function. The Kotlin List. indexOf() function finds and returns the index of first occurrence of the element in the list.
In any lists, you can find the position of an element using the functions indexOf() and lastIndexOf() . They return the first and the last position of an element equal to the given argument in the list.
To find index of substring in this string in Kotlin, call indexOf() method on this string, and pass the substring as argument. String. indexOf() returns an integer representing the index of first occurrence of the match for the given substring.
You can use indexOfFirst
arrayOf(1, 2, 3).indexOfFirst { it == 2 } // returns 1
arrayOf(4, 5, 6).indexOfFirst { it < 3 } // returns -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With