Home > Net >  Is there a Kotlin equivalent for Groovy's findIndexValues?
Is there a Kotlin equivalent for Groovy's findIndexValues?

Time:09-22

Does Kotlin have something to filter a collection and return the matching indexes?

E.g. like Groovy's findIndexValues: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Iterable.html#findIndexValues(groovy.lang.Closure)

Something like:

    fun <T> List<T>.findIndexValues(predicate: (T) -> Boolean): List<Int> {
        var indexValues = mutableListOf<Int>()
        this.forEachIndexed { index, it ->
            if (predicate(it)) {
                indexValues.add(index)
            }
        }
        return indexValues
    }

CodePudding user response:

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.

CodePudding user response:

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()
}
  • Related