Is there a Kotlin equivalent for Groovy's findIndexValues?

Viewed 85
3 Answers

The simplest way I can think of to do this is to use mapIndexedNotNull:

fun <T> List<T>.findIndexValues(predicate: (T) -> Boolean): List<Int> =
    mapIndexedNotNull { i, t -> i.takeIf { predicate(t) } }

I don't believe there's a function for this in the standard library.

There are basically 2 simple ways according to me.

//say there is a List x of Strings
val x = listOf<String>()

//I don't believe you are looking for this.
//string is the required String of x at index.
for ((index, string) in x.withIndex()) {
      TODO()
}

//2nd method is using filterIndexed

/**
 * Returns a list containing only elements matching the given predicate.
 * @Params: predicate - function that takes the index of an element and the element itself and returns the result of predicate evaluation on the element.
 */
x.filterIndexed { index, string ->
      TODO()
}

I like @Sam's answer, but I find this implementation to be slightly more readable as it filters explicitly on predicate as opposed to implicitly via null:

fun <T> List<T>.findIndexValues(predicate: (T) -> Boolean): List<Int> =
    withIndex().filter { (_, t) -> predicate(t) }.map { it.index }
Related